Implementation:Tensorflow Tfjs Tf LoadLayersModel
Summary
tf.loadLayersModel is the primary TensorFlow.js API for loading a pre-trained Keras-style layers model from a URL or custom I/O handler. It fetches the model topology (architecture) and binary weight files, deserializes them, and returns a fully reconstructed LayersModel ready for inference or further training.
API
tf.loadLayersModel(pathOrIOHandler: string|io.IOHandler, options?: io.LoadOptions): Promise<LayersModel>
Source
tfjs-layers/src/models.ts:L248-270
Type
API Doc
Signature
export async function loadLayersModel(
pathOrIOHandler: string|io.IOHandler,
options?: io.LoadOptions
): Promise<LayersModel>
// LoadOptions
// {
// strict?: boolean (default true),
// onProgress?: (fraction: number) => void
// }
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
pathOrIOHandler |
io.IOHandler | Yes | URL to the model.json file, or a custom IOHandler for loading from non-HTTP sources (e.g., local filesystem, IndexedDB)
|
options |
io.LoadOptions |
No | Optional configuration for the loading process |
LoadOptions
| Option | Type | Default | Description |
|---|---|---|---|
strict |
boolean |
true |
If true, all model weights must match loaded weights exactly; mismatches throw an error |
onProgress |
(fraction: number) => void |
undefined | Callback invoked during weight download with a fraction (0 to 1) indicating progress |
I/O
- Inputs: URL to
model.jsonor anIOHandlerinstance, plus optional load options - Outputs:
Promise<LayersModel>with both model topology and weights fully loaded
Loading Process
The function performs the following steps internally:
- Parse the
model.jsonto extract the model topology and weight manifest. - Resolve binary weight shard URLs relative to the
model.jsonlocation. - Download all binary weight shards (potentially in parallel).
- Deserialize the binary data into typed arrays matching each weight's dtype and shape.
- Reconstruct the model architecture from the topology.
- Assign loaded weight values to the corresponding model variables.
Example
// Load pretrained GPT-2 weights
const model = await tf.loadLayersModel(
'https://storage.googleapis.com/gpt2/model.json',
{onProgress: (frac) => console.log(`${(frac*100).toFixed(0)}% loaded`)}
);
Implements
Principle:Tensorflow_Tfjs_Pretrained_Weight_Loading
Environment:Tensorflow_Tfjs_Browser_Runtime Heuristic:Tensorflow_Tfjs_Backend_Selection_Strategy
Domains
Sources
Related Pages
Environments
- Environment:Tensorflow_Tfjs_Browser_Runtime -- Browser runtime (WebGL / WebGPU / WASM / CPU backends)
Heuristics
- Heuristic:Tensorflow_Tfjs_Backend_Selection_Strategy -- Choose the optimal compute backend for your environment