Python SDK

neural_studio lets any Python process create a run on the Experiments page and stream metrics, console output, system telemetry, model statistics, artifacts and media to it, and move files in and out of buckets. Inside a Neural Studio runtime it needs no setup; anywhere else it needs an API key.

import neural_studio as ns

run = ns.init(name="resnet-baseline", project="resnet", config={"lr": 3e-4, "batch_size": 256}, tags=["baseline"])

for step, batch in enumerate(loader):
    loss = train_step(batch)
    run.log({"loss": loss, "lr": scheduler.get_last_lr()[0]}, step=step)

run.finish()  # also runs automatically at process exit

Installing

  • In a runtime: the SDK is preinstalled in every environment image, and a provider-default runtime installs it into the kernel's virtual environment at boot, so import neural_studio works in a notebook cell and in the terminal. The image carries no optional extras. For GPU telemetry run pip install nvidia-ml-py; for images from arrays, JPEG or WebP encoding and Pillow inputs run pip install numpy Pillow; for videos from arrays pip install imageio-ffmpeg; for .laz lidar files pip install "laspy[lazrs]". Do not run pip install "neural-studio[media]" inside a runtime: it would replace the preinstalled SDK with the release on PyPI.
  • Anywhere else: pip install neural-studio (Python 3.10 to 3.13; the only dependencies are requests and psutil). The extras are neural-studio[gpu] (NVML bindings for GPU telemetry), neural-studio[media] (numpy and Pillow), neural-studio[video] (an ffmpeg for videos from arrays) and neural-studio[lidar] (.laz files). The package also installs the ns command.

Authentication

Inside a runtime the kernel and the web terminal carry a session key, so ns.init authenticates on its own and the workspace is known. Outside, a full-access API key is resolved in this order, first hit wins:

  1. the NEURAL_STUDIO_API_KEY environment variable;
  2. the api_key= argument to ns.init;
  3. inside a runtime only, the session key;
  4. api_key = "ns_..." in the config file.

The config file is the first of these that exists: $NEURAL_STUDIO_CONFIG, $XDG_CONFIG_HOME/neural-studio/config.toml, ~/.config/neural-studio/config.toml, ~/.neural-studio/config.toml. It is TOML with four keys: api_key, api_url, workspace (the default workspace id for the bucket calls) and project (the default project of a run). The API base URL is api_url=, then NEURAL_STUDIO_API_URL, then the config file, then https://api.neuralstudio.co. The key travels in the X-API-Key header.

A session key can only create and feed runs, and use the buckets visible, in its own workspace; a full-access key can also read run data, open SSH and use buckets and the workspace's own files (the Files API) in any of your workspaces. Neither can launch a runtime or touch notebooks, environments, secrets or billing.

ns.init

ns.init(name, **options) creates the run and returns a Run handle. All options are keyword-only.

Every run belongs to a project, and the Experiments page shows one project at a time. A project is created the first time a run names it; names are unique in a workspace and ignore case, so "ResNet" and "resnet" are the same project. A run in an archived project brings the project back.

ArgumentDefaultWhat it does
namerequired1 to 200 characters.
projectrequiredThe run's project, by name: 1 to 100 characters, no control characters. When it is not passed, the NEURAL_STUDIO_PROJECT environment variable and then the config file's project key are used; with none of the three, ns.init raises NeuralStudioValidationError before contacting the server.
configNoneA dict of hyperparameters; the server's copy seeds run.config.
tagsNoneA list of strings.
workspaceNoneThe workspace's UUID. Required outside a runtime, also in offline mode; inside a runtime it defaults to the session's workspace, and echo $NEURAL_STUDIO_WORKSPACE_ID in the terminal prints it. Names are not accepted.
descriptionNoneUp to 4,000 characters.
api_keyNoneSee the resolution order above.
api_urlNoneHighest priority for the API base URL.
enable_system_metricsTrueStarts the background sampler (below). When False, samples passed to run.log_system_metrics are not sent either.
system_metrics_interval15.0Seconds between samples; must be positive.
autocaptureTrueRecords the Python version, platform, installed packages, CUDA availability and version, and the git commit, branch and dirty flag when the working directory is a repository. There are no framework hooks: nothing patches PyTorch, TensorFlow or JAX.
rankNoneDistributed rank, else the RANK then LOCAL_RANK environment variables, else 0. Every rank logs to the same run.
mode"online""offline" never opens a socket; see Offline runs.
settingsNoneAn ns.Settings (below).
capture_consoleTrueTees Python-level sys.stdout and sys.stderr into the run's Logs tab. Output reaches the terminal first and capture never blocks; \r redraws (tqdm) collapse to about one line a second. Writes that bypass sys.stdout are not captured.

ns.init also installs an exception hook and an exit hook, so a run that is never finished by hand is still closed when the process ends (see finish). There is no group, resume or context-manager form, and no module-level log function: log through the handle.

An SDK older than 0.4.0 has no project argument, and the server refuses its runs with status 400 and code runs.project_required. Inside a runtime, rebuild the environment to get the current SDK.

The run handle

run.id, run.workspace_id, run.name, run.account_id, run.project (the project's name as you passed it), run.project_id (its id; None for an offline run until it is synced) and run.rank are plain attributes. The rest:

  • run.log(metrics, step=None) appends scalars and never blocks: points land in an in-memory ring, a sealer thread writes them to a local SQLite spill file, and a sender thread ships gzip batches with retries. Names are 1 to 200 characters; bool becomes 0 or 1; NaN and Inf are accepted and the charts mark divergence instead of dropping it. step is a non-negative int; when omitted, each metric counts its own steps from 0. Values may also be media (below). Logging after finish raises RuntimeError.
  • run.config is a live mapping. run.config.update({...}) and run.config["epochs"] = 10 merge at the top level (a nested dict replaces the stored one) and send a background update; one update is at most 256 KiB of JSON. Offline runs journal updates for ns runs sync.
  • run.summary is a read-only {metric: {"last", "min", "max", "step"}} maintained locally with the server's rules: last and step only move forward, NaN and Inf never enter min or max.
  • run.step is the last explicit step or the highest automatic one.
  • run.finished is True once finish ran.

Images, tables and histograms

A value in run.log may be one media object or a list of 1 to 256 of the same kind. A key keeps one kind of media for the life of the run, and media keys match ^[\w\-./: ]+$.

run.log({
    "samples": [ns.Image(img.cpu().numpy(), caption=label) for img, label in examples],
    "predictions": ns.Table(columns=["id", "label", "score"], data=rows),
    "fc_weights": ns.Histogram(model.fc.weight),
}, step=step)
  • ns.Image(data, caption=None, *, format=None, thumbnail=True) takes PNG, JPEG or WebP bytes, a path to such a file, a numpy array (HxW, or HxWxC with 1 to 4 channels; floats in [0, 1] are scaled, booleans become 0 or 255) or a Pillow image. A torch tensor is not accepted: pass tensor.cpu().numpy(). Arrays are encoded as PNG with the standard library; format="jpeg" or "webp" and Pillow inputs need Pillow. Arrays larger than 4,096 px a side or 16.8 megapixels are downscaled; encoded bytes over those limits or over 4 MiB are refused. Captions are at most 500 characters.
  • ns.Table(columns=None, data=None, *, dataframe=None, caption=None) takes columns plus rows, or a pandas dataframe=. Cells are text (at most 10,000 characters), numbers, booleans or None; a non-finite number becomes None. At most 10,000 rows, 200 columns and 8 MiB as JSON.
  • ns.Histogram(values=None, *, bins=64, counts=None, edges=None, caption=None) cuts raw values (a list, a numpy array or a torch tensor; non-finite values are dropped) into bins equal bins, or takes explicit counts and one more strictly increasing edges. 1 to 512 bins.

Video, 3D objects, Gaussian splats and depth maps

The same run.log takes four more kinds of media, shown on the run's Media tab and in dashboard panels with a viewer of their own.

run.log({
    "rollout": ns.Video(frames, fps=30),                      # (T, H, W, 3) uint8
    "cloud": ns.Object3D(points, colors=rgb, boxes=[ns.Box3D(center=c, size=s, label="chair")]),
    "scene": ns.GaussianSplat("point_cloud.ply"),
    "depth": ns.DepthMap(pred, unit="m"),                     # (H, W) floats
}, step=step)
  • ns.Video(data, caption=None, *, fps=24, format=None, thumbnail=True) takes an MP4 (H.264 or AV1), WebM (VP8, VP9 or AV1) or GIF file, as a path or bytes, sent as it is, or an array of frames (T x H x W, or T x H x W x C with 1, 3 or 4 channels; uint8 or floats in [0, 1]; a torch tensor too). An array is encoded to H.264 by the ffmpeg program: pip install "neural-studio[video]" brings one, and one on the PATH is used too; format="webm" or "gif" picks the others. With no ffmpeg the clip is sent as a GIF, with one warning. HEVC and MPEG-4 Part 2 files (what OpenCV's mp4v writes) are refused at the call, with the command that re-encodes them.
  • ns.Object3D(data, caption=None, *, colors=None, faces=None, boxes=None, up=None, thumbnail=True) takes points (N x 3, or N x 6 / N x 7 with colour, or colors= beside them), a mesh (vertices with faces=, an M x 3 array of vertex indices), a file (.glb, .gltf with its side files, .ply, .obj, .stl, .off, .pcd, .las, and .laz with pip install "neural-studio[lidar]"), an open3d point cloud or triangle mesh, or a trimesh object. Everything is sent as one .glb; a .glb file passes through as it is, Draco or Meshopt compression and animations included. up ("y", "z" or "-y") says which way is up for the viewer; the data is never rotated.
  • ns.Box3D(corners=None, *, center=None, size=None, rotation=None, label=None, color=None, score=None) is a labelled wire box for boxes=: eight corners, or a centre and a size with an optional rotation (a 3 x 3 matrix or an x y z w quaternion).
  • ns.GaussianSplat(data, caption=None, *, up=None, max_sh=3, thumbnail=True, format=None) takes the .ply that 3D Gaussian Splatting trainers write, an .spz, .splat or .ksplat file, or arrays through ns.GaussianSplat.from_arrays(means, scales, rotations, opacities, colors, *, sh=None, ...). It is sent as SPZ, about a tenth of the size of the .ply. max_sh (0 to 3) caps the view-dependent colour kept.
  • ns.DepthMap(data, caption=None, *, unit="m", near=None, far=None, dtype="float32", thumbnail=True) takes a 2-D numpy array or torch tensor and sends the numbers themselves, so the viewer shows the distance under the cursor and can compare runs. A value that is not finite means "no depth". unit is "m", "cm", "mm", "km", "ft", "in" or None for relative depth; near and far set the colour range.

These need numpy (pip install numpy in a runtime). Where it can, the SDK also draws a small preview picture of each item, shown before the item itself is loaded. A point cloud or splat scene over the limits is made to fit, with one warning; a mesh over them is refused. A server that does not accept one of these kinds yet discards that kind for the run, with one warning, and keeps sending the rest.

In a notebook, any of these objects as a cell's last expression shows in its viewer under the cell, up to 8 MB each; log larger ones to a run.

Media is encoded on a background thread and sent in batches of up to 256 items or 32 MiB; a video, 3D object, splat scene or depth map over 8 MiB is sent on its own. The per-run and per-workspace caps are on the limits page.

Artifacts and attention maps

  • run.log_artifact(name, data, *, kind="file", content_type=None, step=None, metadata=None) attaches a file and never blocks. data is bytes, a path (opened on the upload thread) or a readable binary file object. Names match ^[\w\-. /]{1,200}$ with no ..; one artifact is at most 64 MiB and metadata at most 8 KiB. The server keys artifacts by (kind, name, step) and the last write wins; step is not defaulted, so an artifact logged without one replaces the previous artifact of that name. Offline runs do not upload artifacts and drop them after one warning.
  • run.log_attention(name, tensor, *, step=None, tokens=None, layer=None, dtype="float32") stores an attention map shaped [T,T], [H,T,T] or [B,H,T,T] (numpy or torch; only batch element 0 is kept) as an attention artifact the Artifacts tab renders as a heatmap. A map over 64 MiB is downcast to float16, and skipped with a warning if it still does not fit.

Checkpoints

run.save_checkpoint(path, *, name="checkpoint", step=None, metadata=None, keep_last=None, stage=True) saves a file or a folder as the next version of the run's checkpoint name and returns at once with a PendingCheckpoint. Training never waits for the upload.

  • With stage=True (the default) the file or folder is first copied into a staging folder (/scratch in a runtime, the system's temporary folder elsewhere), so your training loop can overwrite the original right away. The copy is plain, never a hard link. With stage=False the files are uploaded from path itself: leave them untouched until the upload is done.
  • The copy is uploaded in the background on its own worker pool, in parallel parts straight to storage, one version at a time, to ns://checkpoints/runs/<run id>/<name>/v<n>/ in the workspace's checkpoints bucket. Its bytes count in the workspace owner's storage pool. The checkpoints bucket is made the first time a run in the workspace saves one; it is read-only for ns cp and data, and it cannot be deleted or shared.
  • name is 1 to 64 letters, digits, ., _ or -. Version numbers start at 1 and only go up for each name. step (a whole number) and metadata (a JSON object of at most 7 KiB) are stored with the version.
  • A version is ready only once every one of its files is stored, so a crash mid-upload never leaves a half-written checkpoint that looks usable.
  • keep_last=N deletes the older ready versions of name beyond the newest N, and only after the new version is ready.
  • PendingCheckpoint has name, step, status (uploading, ready or failed), version, checkpoint (the stored Checkpoint once known), error, files_done and bytes_done. wait(timeout=None) blocks until it is ready or failed and returns the Checkpoint, or None when it failed.
  • A checkpoint that fails (the storage pool is full, the run was deleted, the store kept refusing a part) logs one warning and releases the storage it held; the run goes on. Its staged copy is kept, and the warning names the folder: a staged copy is deleted only once its version is ready.
  • run.finish() waits for every checkpoint with no time limit and prints progress every 10 seconds while it waits.
  • While the workspace is read-only (its owner is suspended), checkpoints wait with the rest of the run, staged copies included, and continue once it is writable again. A version that ended during the wait (an upload that is not finished within a day ends failed) is saved again from the staged copy as a new version, with the same name, step, metadata and keep_last. If the run finishes while still paused, the checkpoints not yet saved are given up, their staged copies are kept, and the finish warning names the folders.

Reading them back, on any machine (a runtime of the same workspace, or a laptop with an API key):

from neural_studio import checkpoints

ckpt = checkpoints.latest(run_id)               # newest ready "checkpoint", or None
if ckpt is not None:
    checkpoints.download(ckpt, "/scratch/resume")
CallWhat it does
checkpoints.list(run, *, name=None)Every stored version of the run's checkpoints, by name, newest version first, ready or not. run is the run handle or a run id.
checkpoints.latest(run, *, name="checkpoint")The newest ready version of name, or None.
checkpoints.download(checkpoint, dst, *, progress=None)Downloads a ready version's files into the folder dst, keeping their layout: a saved file lands as dst/<its name>. Returns dst. An interrupted download resumes when it is run again. A version that keep_last deletes while it is being downloaded (a newer one became ready) makes the download fail: call checkpoints.latest again and download that one.

A Checkpoint has id, run_id, workspace_id, name, version, step, status, ready, size_bytes, file_count, address (its folder as an ns:// address), prefix, metadata, keep_last, error_code, created_at and ready_at. The Checkpoints tab of the run lists the versions with a download link per file.

Model watching

run.watch(model, *, log="gradients", log_freq=100, stats=None, max_params=1024, scaler=None) registers hooks on a torch.nn.Module (PyTorch must be importable; the SDK never installs it). Every log_freq backward passes it records gradients/<param>/norm, parameters/<param>/<stat> and gradients/global_norm at the run's current step, right before the next run.log call's own points. log is "gradients", "parameters" or "all"; stats picks parameter statistics from norm, mean, std, absmax and zero_frac (default norm, mean, std) and is ignored for gradient-only watching; at most max_params parameters are watched, in model order. The returned watcher exposes manifest, watched_names, flush_pending() and remove(). A second call replaces the first. run.unwatch() flushes and detaches the hooks.

System metrics

A background thread samples the machine's CPU percentage and RAM in use through psutil, and per-GPU utilisation, memory, temperature and power through NVML when pynvml is importable. One sample every system_metrics_interval seconds, posted in batches of four. The System tab of the run shows them. run.log_system_metrics(sample) injects a sample by hand (keys cpu_percent, ram_used_bytes, gpu_utilization, gpu_memory_bytes, gpu_temperature_c, gpu_power_w); it needs the sampler to be enabled and raises RuntimeError in offline mode.

Finishing a run

run.finish(exit_code=0, *, timeout=30.0, status=None) is idempotent. The status is completed for exit code 0 and failed otherwise, unless status names one of completed, failed, stopped or disconnected. Within timeout seconds it detaches run.watch, stops console capture and the sampler, drains metrics (60% of the time left), console lines, media and uploads, logs one warning naming anything left behind, then marks the run finished on the server. Whatever could not be delivered stays in the spill file, with the finish owed, for ns runs sync. Checkpoints are the one exception to timeout: finish waits for every one of them, however long it takes, and prints progress while it waits.

While the owner of the run's workspace is suspended, the workspace is read-only: the server refuses every write to the run with HTTP 409 workspace.owner_suspended ("The owner of this workspace is suspended, so it is read-only for now."). The run pauses: one warning says so in those words, and from then on nothing is sent and everything is kept. Metric batches and media stay in the spill file, and console lines, system metrics, config updates, model-watch manifests and artifacts wait in memory. About once a minute one small request checks the workspace again. When the suspension is lifted, logging resumes by itself, sends what was kept in order, and one line says so. If the run finishes while paused, everything still waiting in memory moves into the spill file (an artifact's bytes are copied there, at most 64 MiB each and 256 MiB in all), the finish stays owed, and the warning says what the file keeps. ns runs sync delivers it in order and finishes the run once the workspace is writable again. System metrics keep the time they were captured.

A long suspension can drop data, and the finish warning counts every drop: console lines past 10,000 and system-metric samples past 1,000 (oldest first); uploads past 256 waiting jobs or 256 MiB; metric batches and media past ns.Settings(paused_spill_cap_bytes=...) (1 GiB by default, oldest media first) or when the disk is full; an artifact whose file object you closed before the run finished; and artifacts past the size caps above.

A process that ends without calling finish is finished by the exit hook within 5 seconds: failed with exit code 1 after an uncaught exception, disconnected otherwise. A run whose process vanishes without either is marked disconnected by the server once its heartbeats stop.

Offline runs and ns runs sync

Every run seals its batches into ./.neural-studio/run-<id>.db (one more file per extra rank, run-<id>-r<rank>.db) before sending them, so a crash or a dead network loses nothing. ns.init(..., mode="offline") goes one step further and never opens a socket: no key is needed, the run gets a local id, and config updates and console lines are journaled too. Artifacts are the exception; they are dropped offline.

ns runs sync       # scans ./.neural-studio and replays anything undelivered
ns runs sync path/to/run-<id>.db

ns runs sync, or ns.sync(path=None) from Python, creates each offline run on the server (folding in the journaled config), replays metric batches, console lines and media, performs any owed finish (an offline run ends completed), and vacuums the file. Each batch carries a fixed id, so a replay is delivered exactly once and running it again is a no-op. Before SDK 0.3.0 the command was ns sync; that form still replays, with a deprecation notice, for one more release, and ns sync <src> <dst> now syncs buckets. ns.sync keeps its name and meaning. Credentials resolve exactly as for ns.init. An offline run recorded by an SDK older than 0.4.0 names no project: ns runs sync --project NAME (or ns.sync(path, project="NAME"), else NEURAL_STUDIO_PROJECT) creates it in that project, and without one the file is kept and reported as pending. The exit code is 0 when nothing is left pending and nothing was discarded, else 1; from Python the SyncReport has files_scanned, runs_created, batches_sent, batches_dropped, log_lines_sent, media_sent, media_dropped, held_sent, held_dropped (what a paused run kept: config updates, manifests, artifacts, system metrics), runs_finished, unfinished, lost and clean.

In a runtime the working directory is ~/workspace, which is durable and counts against your storage pool. Keep the spill on the local disk instead:

run = ns.init(name="...", project="...", settings=ns.Settings(spill_dir="/tmp/ns-spill"))

Settings

ns.Settings is a frozen dataclass of pipeline knobs, all optional: ring_size (65,536 points in memory), seal_max_points (5,000), seal_interval_s (2.0), send_backoff_base_s (0.5), send_backoff_cap_s (60.0), spill_dir (./.neural-studio) and heartbeat_idle_s (30.0).

Workspace secrets

Inside a runtime, every secret the environment references by name is an environment variable. ns.secrets.get("HF_TOKEN") reads it and raises KeyError with a message that says why when it is absent (not defined in the workspace, not referenced by the environment, or not inside a runtime); ns.secrets.get(name, default) returns the default instead. ns.secrets.names() and ns.secrets.missing() list the names that were injected and the referenced names that did not resolve. Nothing here calls the API. See Isolation and secrets.

Buckets

neural_studio.data (SDK 0.3.0 and later) moves files between this machine and buckets, and is what the ns bucket commands run. Addresses are ns://<bucket>/<path>; a trailing slash means a folder.

import pyarrow.parquet as pq
from neural_studio import data

data.create_bucket("my-data")
data.upload("checkpoints/", "ns://my-data/run-7/", recursive=True)
data.download("ns://my-data/run-7/model.pt", "/scratch/")
data.sync("ns://my-data/dataset/", "/scratch/dataset", delete=True)

for entry in data.ls("ns://my-data/run-7/"):
    print(entry.name, "folder" if entry.is_folder else entry.size_bytes)

with data.open("ns://my-data/dataset/train.parquet") as f:
    table = pq.read_table(f)  # reads byte ranges, no download

Inside a runtime every call works in the runtime's workspace with its session key. Elsewhere the key resolves as above and the workspace is workspace=, then NEURAL_STUDIO_WORKSPACE_ID, then workspace in the config file (Workspace settings shows the id). A data key in NEURAL_STUDIO_API_KEY is enough for every call here: scope data:write to read and write, data:read to read only, chosen under Account settings → API keys. It reaches nothing else; see API keys.

CallWhat it does
data.upload(src, dst, *, recursive=False, exclude=None, include=None, content_type=None, dryrun=False, workspace=None, progress=None)A local file, or with recursive a folder's contents, to a bucket. The content type is guessed from the extension unless given.
data.download(src, dst, *, recursive=False, exclude=None, include=None, dryrun=False, workspace=None, progress=None)An object, or a folder, to a local path. An existing local folder receives the object under its own name.
data.copy(src, dst, ...)Any direction, like ns cp. Between two buckets the copy happens in storage.
data.mv(src, dst, ...)copy, then each source is removed once its copy is complete.
data.rm(target, *, recursive=False, exclude=None, include=None, dryrun=False, workspace=None, progress=None)Deletes an object, or everything under a folder.
data.sync(src, dst, *, delete=False, checksum=False, exclude=None, include=None, content_type=None, dryrun=False, workspace=None, progress=None)Copies what is new or changed (size or modification time differ). With checksum, content is compared by SHA-256: local files are hashed, a bucket file's hash is the one its uploader declared (a checksum upload declares each file's hash; the server stores it unverified), and a file the bucket has no hash for is copied. delete removes extras in dst, and is skipped when a copy failed.
data.ls(target=None, *, recursive=False, workspace=None)With no target, the workspace's buckets as Bucket items (name, access, read_only, used_bytes, object_count, kind, created_at). With a folder, FolderEntry items then ObjectEntry items (path, name, size_bytes, etag, content_type, mtime, and sha256 as declared by the uploader, or None); recursive lists every object under it.
data.open(target, mode="rb", *, encoding=None, workspace=None)A seekable, read-only file object that fetches byte ranges as you read (8 MiB read-ahead). mode="r" gives text.
data.credentials(bucket, *, workspace=None)One-hour, read-only S3 credentials for one bucket, as a BucketCredentials: access_key_id, secret_access_key, session_token, expiration, region, endpoint_url, and uri, the bucket's s3:// root in storage. as_credential_process() gives the JSON ns credentials prints.
data.create_bucket(name, *, workspace=None)A bucket visible, read-write, in this workspace only. It belongs to the account that owns the workspace.
data.delete_bucket(name, *, force=False, workspace=None)force=True also deletes what is in it.

exclude and include take a pattern or a list of shell patterns matched against each path relative to the source folder (* also matches /). Excludes apply first and includes win over them, so exclude="*", include="*.csv" copies only CSV files.

Every call that moves files returns a TransferReport with done, skipped and failed lists of TransferItem (action, source, dest, size, and code and message on a failure), plus ok, bytes_transferred, quota_message and notes. When any file failed the call raises ns.NeuralStudioTransferError, whose report is the same report; the files that did arrive stay. progress, when given, is called with each TransferItem as it settles. Running a call again resumes it: unchanged files are skipped by sync, an upload interrupted within the last 24 hours sends only its missing parts (if the file's size and modification time are unchanged), and a download over 64 MiB continues from its hidden .<name>.ns-<12 hex>.part file and .part.json beside the destination. Bytes go straight between this machine and storage, 16 parts at a time. A file that changes while it is being uploaded, or an object replaced while it is being downloaded, fails rather than being stored half old and half new. Folder links are followed; an unreadable folder, a link loop, and a pipe, socket or device fail instead of being skipped, which also holds back delete. Two objects that would land on one local name fail with code local.collision before anything is written; whether names that differ only in letter case or Unicode form are one name is measured on the destination disk with a small hidden probe file, created and removed once per run.

The workspace's own files

ns://workspace/<path> names a file or folder of the workspace itself (the Files page), and every call above that moves, lists, deletes or opens files takes it (SDK 0.3.0 and later):

data.upload("train.py", "ns://workspace/code/")
data.download("ns://workspace/results/", "results", recursive=True)
data.sync("notebooks/", "ns://workspace/notebooks/", delete=True)

Inside a runtime the address is the local ~/workspace folder, so every call is a plain file operation there, the session key is not used for it, and a bucket on the other side works in both directions (an upload from the folder, or a download into it). The platform's hidden .ns-cache and .ns-uploads folders are never copied, synced over or deleted, and a link that leads outside the workspace is never followed: naming one is refused, and one met while copying a folder fails with code source.link_escapes. A move inside the workspace never replaces an existing file.

On a laptop or cluster the calls go through the Files API with your API key: data:read lists and downloads, data:write (or a full-access key) also uploads, moves and deletes, with your role in the workspace deciding as on the Files page. Every byte passes through the API, at about 12 MB/s, which suits code and notebooks; keep large data in a bucket. A file is uploaded or downloaded in one request: a dropped connection starts that file again (no resume), and an interrupted upload leaves the old file in place. A folder download is one zip stream per 50 top-level entries, unpacked with every entry checked: a path that would leave the destination, a link, and a device or pipe in the archive fail with codes archive.unsafe_path and archive.not_regular, and nothing is written through a link already in the destination (local.unsafe_path). A folder over the API's archive limits (10,000 entries or 20 GiB) fails with code validation.archive_too_large; sync fetches file by file instead. sync sends a file when it is missing, its size differs, or the source is newer: the workspace records when a file was written, not the uploader's time, and keeps no checksums, so with checksum every file is sent. Two files whose names are one name on your disk (letter case, or Unicode form, on macOS and Windows) fail with code local.collision and are not written, and mv leaves them in the workspace. A folder that changes while it is being listed fails with code files.listing_changed before anything is deleted. mv inside the workspace is a rename on the server and never replaces an existing file (code files.conflict); open from a laptop reads forward only.

From a laptop or cluster these raise WorkspaceTransferUnavailableError (a NeuralStudioValidationError with a code) and transfer nothing:

  • between a bucket and ns://workspace/, either way (code workspace.bucket_transfer_unavailable), except copy and mv from the workspace into a bucket: syncing between them is not available from a laptop; inside a runtime use the local folder.

data.mv("ns://workspace/<folder>/", "ns://<bucket>/<folder>/", recursive=True) (or one file into a folder) from a laptop runs Move to bucket on the server and returns when it ends: one move item for the whole job, or a NeuralStudioTransferError whose failed item carries the job's error code and message (nothing is deleted then). data.copy with the same arguments runs the same job and deletes nothing. A move needs the workspace's runtime stopped (code transfer.runtime_running otherwise). It needs a full-access or data:write API key; include / exclude are refused, and so is the workspace's top level;

  • copy or sync from ns://workspace/ to ns://workspace/ (code workspace.copy_unavailable): it would pass every byte through your machine; mv it, or copy it inside a runtime.

A call that takes a bucket name (data.credentials, data.create_bucket, data.delete_bucket) refuses ns://workspace, which is not a bucket.

Errors

All SDK errors derive from ns.NeuralStudioError: NeuralStudioAuthError (no key could be resolved), NeuralStudioValidationError (a bad argument; also a ValueError), NeuralStudioConfigError (an unreadable config file), NeuralStudioAPIError (a non-2xx response, with status_code, code, message and details; a network failure has status_code 0 and code network.error; a redirect from the API is never followed, so the key goes nowhere else, and raises one with code response.redirect), NeuralStudioQuotaError (an NeuralStudioAPIError for a bucket upload or copy the account's storage pool has no room for; its message states what was needed and what is free) and NeuralStudioTransferError (a bucket call in which some files failed; see Buckets). ns.init in a workspace whose owner is suspended raises NeuralStudioAPIError with status 409 and code workspace.owner_suspended; see Finishing a run for a run already logging there. A finished run raises plain RuntimeError on log, and an unknown finish status raises ValueError.

Environment variables

VariableMeaning
NEURAL_STUDIO_API_KEYAPI key; wins over every other source.
NEURAL_STUDIO_API_URLAPI base URL.
NEURAL_STUDIO_CONFIGPath of the config file to read first.
NEURAL_STUDIO_PROJECTThe run's project when ns.init is not passed one; also the project ns runs sync gives an offline run recorded without one.
NEURAL_STUDIO_SESSION_API_KEYSet in a runtime: the session key, and the signal that the SDK is inside a runtime.
NEURAL_STUDIO_WORKSPACE_ID, NEURAL_STUDIO_SESSION_IDSet in a runtime: the default workspace and the session the run is attached to. Outside a runtime you may set NEURAL_STUDIO_WORKSPACE_ID yourself as the bucket calls' default workspace.
RANK, LOCAL_RANKDefault distributed rank.
NS_USER_SECRET_NAMES, NS_USER_SECRETS_MISSINGSet in a runtime: the manifests behind ns.secrets.