Load a ComputationGraph for the given checkpoint from the specified root direcotry

@param checkpoint Checkpoint model to load
@return The loaded model
502810
public static ComputationGraph loadCheckpointCG(File rootDir, Checkpoint checkpoint){
        return loadCheckpointCG(rootDir, checkpoint.getCheckpointNum());
    }
820551
def advance_to_checkpoint(self, checkpoint):
        
        if checkpoint in self._checkpoints:
            for cp in self._checkpoints:
                self.insert(cp)
                if cp == checkpoint:
                    return cp
        else:
            raise InvalidCheckpointError(checkpoint)
1245393
public static ComputationGraph restoreComputationGraph(@NonNull InputStream is, boolean loadUpdater)
            throws IOException {
        checkInputStream(is);

        File tmpFile = null;
        try{
            tmpFile = tempFileFromStream(is);
            return restoreComputationGraph(tmpFile, loadUpdater);
        } finally {
            if(tmpFile != null){
                tmpFile.delete();
            }
        }
    }
1360164
def load(self, filename):
        
        if os.path.isfile(filename):
            checkpoint = torch.load(filename, map_location={'cuda:0': 'cpu'})
            if self.distributed:
                self.model.module.load_state_dict(checkpoint['state_dict'])
            else:
                self.model.load_state_dict(checkpoint['state_dict'])
            self.fp_optimizer.initialize_model(self.model)
            self.optimizer.load_state_dict(checkpoint['optimizer'])
            self.scheduler.load_state_dict(checkpoint['scheduler'])
            self.epoch = checkpoint['epoch']
            self.loss = checkpoint['loss']
            logging.info(f'Loaded checkpoint {filename} (epoch {self.epoch})')
        else:
            logging.error(f'Invalid checkpoint: {filename}')
808128
public static Checkpoint lastCheckpoint(File rootDir){
        List<Checkpoint> all = availableCheckpoints(rootDir);
        if(all.isEmpty()){
            return null;
        }
        return all.get(all.size()-1);
    }
309457
def checkpoint_parameter_from_file(node_type, parameter)
      Bebox::Node.checkpoint_parameter_from_file(self.project_root, self.environment, self.hostname, node_type, parameter)
    end
17315
public synchronized void restoreFromCheckpoint(CheckpointInputStream input) throws IOException {
    LOG.info("Restoring rocksdb from checkpoint");
    long startNano = System.nanoTime();
    Preconditions.checkState(input.getType() == CheckpointType.ROCKS,
        "Unexpected checkpoint type in RocksStore: " + input.getType());
    stopDb();
    FileUtils.deletePathRecursively(mDbPath);
    TarUtils.readTarGz(Paths.get(mDbPath), input);
    try {
      createDb();
    } catch (RocksDBException e) {
      throw new IOException(e);
    }
    LOG.info("Restored rocksdb checkpoint in {}ms",
        (System.nanoTime() - startNano) / Constants.MS_NANO);
  }
1206843
private void doCheckpoint() throws IOException {
    long start = AvatarNode.now();
    try {
      InjectionHandler.processEvent(InjectionEvent.STANDBY_ENTER_CHECKPOINT, this.sig);
      
      // Tell the remote namenode to start logging transactions in a new edit file
      // Retuns a token that would be used to upload the merged image.
      if (!checkpointEnabled) {
        checkpointStatus("Disabled");
        // This means the Standby is not meant to checkpoint the primary
        LOG.info("Standby: Checkpointing is disabled - return");
        return;
      }
      CheckpointSignature sig = null;
      InjectionHandler.processEvent(InjectionEvent.STANDBY_BEFORE_ROLL_EDIT);
      try {
        LOG.info("Standby: Checkpointing - Roll edits logs of primary namenode "
            + nameNodeAddr);
        checkpointStatus("Edit log rolled on primary");
        synchronized(ingestStateLock) {
          sig = (CheckpointSignature) primaryNamenode.rollEditLog();
        }
      } catch (IOException ex) {
        // In this case we can return since we did not kill the Ingest thread yet
        // Nothing prevents us from doing the next checkpoint attempt
        checkpointStatus("Checkpoint failed");
        LOG.warn("Standby: Checkpointing - roll Edits on the primary node failed.");
        InjectionHandler.processEvent(
            InjectionEvent.STANDBY_EXIT_CHECKPOINT_FAILED_ROLL, ex);
        return;
      }
      
      setLastRollSignature(sig); 
      
      // consume all finalized log segments up to the required txid
      long checkpointTxId = sig.curSegmentTxId - 1;  
      LOG.info("Standby: Checkpointing - checkpoint txid: " + checkpointTxId);
      checkpointStatus("Quiescing ingest");
      quiesceIngest(checkpointTxId);
      
      if (currentSegmentTxId != checkpointTxId + 1) {
        throw new IOException(
            "Standby: Checkpointing txid mismatch - ingest consumed txns up to "
                + (currentSegmentTxId - 1) + " but should have up to "
                + checkpointTxId);
      }
      
      // if everything is fine, the edit log should be closed now
      LOG.info("Standby: Checkpointing - finished quitting ingest thread just before ckpt.");       
      assertState(StandbyIngestState.NOT_INGESTING);
  
      /**
       * From now on Ingest thread needs to know if the checkpoint was started and never finished.
       * This would mean that it doesn't have to read the edits, since they were already processed
       * to the end as a part of a checkpoint. state = StandbyIngestState.CHECKPOINTING
       */
      fsnamesys.writeLock();
      try {      
        InjectionHandler.processEvent(InjectionEvent.STANDBY_BEFORE_SAVE_NAMESPACE);
        currentIngestState = StandbyIngestState.CHECKPOINTING;
    
        // save a checkpoint of the current namespace of the local Namenode
        // We should ideally use fsnamesystem.saveNamespace but that works
        // only if namenode is not in safemode.
        LOG.info("Standby: Checkpointing - save fsimage on local namenode.");
        checkpointStatus("Saving namespace started");
        // by default checkpoints are compressed if configured
        // manual command can override this setting for one checkpoint
        fsnamesys.getFSImage().saveNamespace(false);
        // get the new signature
        sig.mostRecentCheckpointTxId = fsImage.getEditLog().getLastWrittenTxId();
        sig.imageDigest = fsImage.storage.getCheckpointImageDigest(sig.mostRecentCheckpointTxId);
      } catch (SaveNamespaceCancelledException e) {
        InjectionHandler.processEvent(InjectionEvent.STANDBY_CANCELLED_EXCEPTION_THROWN);
        LOG.info("Standby: Checkpointing - cancelled saving namespace");
        fsnamesys.getFSImage().deleteCheckpoint(checkpointTxId);
        throw e;
      } catch (IOException ex) {
        // Standby failed to save fsimage locally. Need to reinitialize
        String msg = "Standby: Checkpointing - failed to checkpoint itself, so " +
        		"no image can be uploaded to the primary. The only course of action " +
        		"is to start from the very beginning by reinitializing AvatarNode";
        LOG.error(msg, ex);
        fsnamesys.getFSImage().deleteCheckpoint(checkpointTxId);
        throw new RuntimeException(msg, ex);
      } finally {
        currentIngestState = StandbyIngestState.NOT_INGESTING;
        fsnamesys.writeUnlock();
      }
      
      // we can start the ingest again for next segment
      instantiateIngest();
      
      try {
        finalizeCheckpoint(sig);
      } catch (IOException ex) {
        LOG.error("Standby: Checkpointing - rolling the fsimage " +
            "on the Primary node failed.", ex);
        throw new FinalizeCheckpointException(ex.toString());
      }
      setCheckpointFailures(0);
      LOG.info("Standby: Checkpointing - checkpoint completed in "
          + ((AvatarNode.now() - start) / 1000) + " s.");
    } catch (IOException e) {
      LOG.error("Standby: Checkpointing - failed to complete the checkpoint: "
          + StringUtils.stringifyException(e));
      checkpointStatus("Checkpoint failed");    
      if (!checkpointEnabled) {
        // we received instruction to prepare for failover
        return;
      }
      handleCheckpointFailure();
      InjectionHandler.processEvent(InjectionEvent.STANDBY_EXIT_CHECKPOINT_EXCEPTION, e);
      throw e;
    } finally {
      countDownManualLatch(1);
      setLastRollSignature(null);
      InjectionHandler.processEvent(InjectionEvent.STANDBY_EXIT_CHECKPOINT, this.sig);
    }
  }
851255
public static ComputationGraph restoreComputationGraph(@NonNull File file, boolean loadUpdater) throws IOException {
        ZipFile zipFile = new ZipFile(file);

        boolean gotConfig = false;
        boolean gotCoefficients = false;
        boolean gotUpdaterState = false;
        boolean gotPreProcessor = false;

        String json = "";
        INDArray params = null;
        INDArray updaterState = null;
        DataSetPreProcessor preProcessor = null;


        ZipEntry config = zipFile.getEntry(CONFIGURATION_JSON);
        if (config != null) {
            //restoring configuration

            InputStream stream = zipFile.getInputStream(config);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line = "";
            StringBuilder js = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                js.append(line).append("\n");
            }
            json = js.toString();

            reader.close();
            stream.close();
            gotConfig = true;
        }


        ZipEntry coefficients = zipFile.getEntry(COEFFICIENTS_BIN);
        if (coefficients != null) {
            if(coefficients.getSize() > 0) {
                InputStream stream = zipFile.getInputStream(coefficients);
                DataInputStream dis = new DataInputStream(new BufferedInputStream(stream));
                params = Nd4j.read(dis);

                dis.close();
                gotCoefficients = true;
            } else {
                ZipEntry noParamsMarker = zipFile.getEntry(NO_PARAMS_MARKER);
                gotCoefficients = (noParamsMarker != null);
            }
        }


        if (loadUpdater) {
            ZipEntry updaterStateEntry = zipFile.getEntry(UPDATER_BIN);
            if (updaterStateEntry != null) {
                InputStream stream = zipFile.getInputStream(updaterStateEntry);
                DataInputStream dis = new DataInputStream(new BufferedInputStream(stream));
                updaterState = Nd4j.read(dis);

                dis.close();
                gotUpdaterState = true;
            }
        }

        ZipEntry prep = zipFile.getEntry(PREPROCESSOR_BIN);
        if (prep != null) {
            InputStream stream = zipFile.getInputStream(prep);
            ObjectInputStream ois = new ObjectInputStream(stream);

            try {
                preProcessor = (DataSetPreProcessor) ois.readObject();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

            gotPreProcessor = true;
        }


        zipFile.close();

        if (gotConfig && gotCoefficients) {
            ComputationGraphConfiguration confFromJson;
            try{
                confFromJson = ComputationGraphConfiguration.fromJson(json);
                if(confFromJson.getNetworkInputs() == null && (confFromJson.getVertices() == null || confFromJson.getVertices().size() == 0)){
                    //May be deserialized correctly, but mostly with null fields
                    throw new RuntimeException("Invalid JSON - not a ComputationGraphConfiguration");
                }
            } catch (Exception e){
                if(e.getMessage() != null && e.getMessage().contains("registerLegacyCustomClassesForJSON")){
                    throw e;
                }
                try{
                    MultiLayerConfiguration.fromJson(json);
                } catch (Exception e2){
                    //Invalid, and not a compgraph
                    throw new RuntimeException("Error deserializing JSON ComputationGraphConfiguration. Saved model JSON is" +
                            " not a valid ComputationGraphConfiguration", e);
                }
                throw new RuntimeException("Error deserializing JSON ComputationGraphConfiguration. Saved model appears to be " +
                        "a MultiLayerNetwork - use ModelSerializer.restoreMultiLayerNetwork instead");
            }

            //Handle legacy config - no network DataType in config, in beta3 or earlier
            if(params != null)
                confFromJson.setDataType(params.dataType());

            ComputationGraph cg = new ComputationGraph(confFromJson);
            cg.init(params, false);


            if (gotUpdaterState && updaterState != null) {
                cg.getUpdater().setStateViewArray(updaterState);
            }
            return cg;
        } else
            throw new IllegalStateException("Model wasnt found within file: gotConfig: [" + gotConfig
                    + "], gotCoefficients: [" + gotCoefficients + "], gotUpdater: [" + gotUpdaterState + "]");
    }
900963
@Override
	public void acknowledgeCheckpoint(
			final JobID jobID,
			final ExecutionAttemptID executionAttemptID,
			final long checkpointId,
			final CheckpointMetrics checkpointMetrics,
			final TaskStateSnapshot checkpointState) {

		final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
		final AcknowledgeCheckpoint ackMessage = new AcknowledgeCheckpoint(
			jobID,
			executionAttemptID,
			checkpointId,
			checkpointMetrics,
			checkpointState);

		if (checkpointCoordinator != null) {
			getRpcService().execute(() -> {
				try {
					checkpointCoordinator.receiveAcknowledgeMessage(ackMessage);
				} catch (Throwable t) {
					log.warn("Error while processing checkpoint acknowledgement message", t);
				}
			});
		} else {
			String errorMessage = "Received AcknowledgeCheckpoint message for job {} with no CheckpointCoordinator";
			if (executionGraph.getState() == JobStatus.RUNNING) {
				log.error(errorMessage, jobGraph.getJobID());
			} else {
				log.debug(errorMessage, jobGraph.getJobID());
			}
		}
	}
529036
protected synchronized void checkpoint(long forcedLogSequenceNumber)
                    throws ObjectManagerException
    {
        throw new InvalidStateException(this, InternalTransaction.stateTerminated, InternalTransaction.stateNames[InternalTransaction.stateTerminated]);
    }
431855
public static MultiLayerNetwork loadLastCheckpointMLN(File rootDir){
        Checkpoint last = lastCheckpoint(rootDir);
        return loadCheckpointMLN(rootDir, last);
    }
965792
def save_model():
    
    if not os.path.exists("checkpoint"):
        os.mkdir("checkpoint")
    return mx.callback.do_checkpoint("checkpoint/checkpoint", args.save_period)
479010
void open(TopologyContext context, SpoutOutputCollector collector,
              int checkpointInterval, KeyValueState<String, CheckPointState> checkpointState) {
        this.context = context;
        this.collector = collector;
        this.checkpointInterval = checkpointInterval;
        this.sleepInterval = checkpointInterval / 10;
        this.checkpointState = checkpointState;
        this.curTxState = checkpointState.get(TX_STATE_KEY);
        lastCheckpointTs = 0;
        recoveryStepInProgress = false;
        checkpointStepInProgress = false;
        recovering = true;
    }
632077
private void checkPoint(Collidable objectA, Map<Point, Set<Collidable>> acceptedElements, Point point)
    {
        final Set<Collidable> others = acceptedElements.get(point);
        for (final Collidable objectB : others)
        {
            if (objectA != objectB)
            {
                final List<Collision> collisions = objectA.collide(objectB);
                for (final Collision collision : collisions)
                {
                    toNotify.add(new Collided(objectA, objectB, collision));
                }
            }
        }
    }
865245
@Override
	public CheckpointStorage createCheckpointStorage(JobID jobId) throws IOException {
		return new MemoryBackendCheckpointStorage(jobId, getCheckpointPath(), getSavepointPath(), maxStateSize);
	}
1060585
def _restore_and_log_checkpoint(self, actor):
        
        actor_id = self._worker.actor_id
        try:
            checkpoints = ray.actor.get_checkpoints_for_actor(actor_id)
            if len(checkpoints) > 0:
                # If we found previously saved checkpoints for this actor,
                # call the `load_checkpoint` callback.
                checkpoint_id = actor.load_checkpoint(actor_id, checkpoints)
                if checkpoint_id is not None:
                    # Check that the returned checkpoint id is in the
                    # `available_checkpoints` list.
                    msg = (
                        "`load_checkpoint` must return a checkpoint id that " +
                        "exists in the `available_checkpoints` list, or eone.")
                    assert any(checkpoint_id == checkpoint.checkpoint_id
                               for checkpoint in checkpoints), msg
                    # Notify raylet that this actor has been resumed from
                    # a checkpoint.
                    (self._worker.raylet_client.
                     notify_actor_resumed_from_checkpoint(
                         actor_id, checkpoint_id))
        except Exception:
            # Checkpoint save or reload failed. Notify the driver.
            traceback_str = ray.utils.format_error_message(
                traceback.format_exc())
            ray.utils.push_error_to_driver(
                self._worker,
                ray_constants.CHECKPOINT_PUSH_ERROR,
                traceback_str,
                driver_id=self._worker.task_driver_id)