Skip to main content
torch.jstorch.jstorch.js
Getting StartedPlaygroundContact
Login
torch.jstorch.jstorch.js
Documentation
IntroductionType SafetyTensor IndexingEinsumEinopsAutogradTraining a ModelProfiling & MemoryPyTorch MigrationBest PracticesRuntimesPerformance
IntroductionQuickstartClient APIWorker APIFile I/OBackends
torch.js· 2026
LegalTerms of UsePrivacy Policy
  1. docs
  2. Spark
  3. Worker API

Worker API

The Worker API is used inside your torch() function. These tools handle state persistence across hot reloads and communication with the UI.

spark.persist()

Preserves an object across code changes during development. This is essential for keeping model weights and optimizer states alive while you edit your training logic.

const model = spark.persist('model_key', () => {
  return nn.Sequential(nn.Linear(10, 10));
});

spark.expose()

Defines the interface that the React UI can see and interact with.

// These will be available on the proxy returned by spark.use()
spark.expose({
  train,
  state,
  resetModel: () => spark.clearPersisted('model_key')
});

spark.checkpoint()

The most important function for cooperative multitasking. It yields execution back to Spark, allowing it to:

  • Pause the loop if the user clicked "Pause".
  • Inject new code if you just saved your file (Hot Reload).
  • Report progress back to the main thread.
async function train() {
  while (true) {
    await spark.checkpoint(); // Yield control;
    runOneIteration();
  }
}

Frequency Matters: Call spark.checkpoint() at least once per training batch. If you call it too rarely, your UI will feel sluggish or unresponsive to control commands.

Next Steps

  • Client API - How to consume these exposed bindings.
  • File I/O - Persisting your work permanently.
Previous
Client API
Next
File I/O