Skip to main content
torch.js has not been released yet.
torch.js logotorch.js logotorch.js
PlaygroundContact
Login
Documentation
IntroductionType SafetyTensor ExpressionsTensor IndexingEinsumEinopsAutogradTraining a ModelProfiling & MemoryPyTorch MigrationBest PracticesRuntimesPerformancePyTorch CompatibilityBenchmarksDType Coverage
torch.js· 2026
LegalTerms of UsePrivacy Policy
/
/
  1. docs
  2. Spark
  3. spark
  4. createSelfRpc

spark.createSelfRpc

function createSelfRpc(): Rpc

Create an RPC instance for the current Web Worker context.

Used in Web Workers to set up RPC handlers and listen for messages from the parent thread.

Equivalent to: new Rpc({ target: self, origin: '*' })

This should typically be called once at the worker entry point to set up the communication channel with the parent.

Returns

Rpc– RPC instance configured for worker context

Examples

// In a Web Worker (worker.js):
import torch from '@torchjsorg/torch.js';
import * as spark from '@torchjsorg/spark';

const rpc = createSelfRpc();

// Register handlers for parent's RPC calls
rpc.handle('train', async (params) => {
  const model = torch.nn.Sequential([...]);
  // ... training logic
  return { loss: 0.5, accuracy: 0.95 };
});

// Send updates to parent
rpc.notify('worker.ready', { loaded: true });

// Handle control messages
rpc.handle('control', (command) => {
  if (command === 'stop') {
    // Stop training
  }
});

See Also

  • createWorkerRpc - Create RPC to worker (from main thread)
  • createParentRpc - Create RPC to parent (from iframe)
Previous
createParentRpc
Next
createWorkerRpc