Skip to content

TorchLens 2.0 API changes

The current TorchLens 2.x surface reserves exactly 85 top-level names in torchlens.__all__. Names outside that budget either moved to a namespace (the old top-level name was removed), remain available only from their canonical namespace, or are implemented top-level helpers that fit inside the public namespace budget.

Attribute access to a removed name (tl.resample_ablate, torchlens.intervention.resample_ablate) raises FacadeTeachingError (code facade_redirect) naming the new path. The from import form (from torchlens import resample_ablate) cannot carry that message: CPython turns the attribute error into a plain ImportError: cannot import name .... Look the name up in this table, or use attribute access to see the redirect.

Old top-level name New path Mechanism Removed in version Tests
FuncCallLocation torchlens.types.FuncCallLocation removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
GradFnAccessor torchlens.appliances.GradFnAccessor removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
GradFn torchlens.types.GradFn removed (was: object alias via __getattr__; removed from __all__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
ActivationPostfunc torchlens.types.ActivationPostfunc removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
Bundle torchlens.Bundle kept top-level none test_api_surface.py
GradientPostfunc torchlens.types.GradientPostfunc removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
LayerAccessor torchlens.appliances.LayerAccessor removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
Layer torchlens.Layer kept top-level none test_api_surface.py
MetadataInvariantError torchlens.errors.MetadataInvariantError removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
ModuleAccessor torchlens.appliances.ModuleAccessor removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
Module torchlens.types.Module removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
NodeSpec torchlens.viz.NodeSpec removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
Param torchlens.types.Param removed (was: object alias via __getattr__; removed from __all__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
TraceState torchlens.io.TraceState removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
SaveLevel torchlens.types.SaveLevel removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
StreamingOptions torchlens.options.StorageOptions removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
SpecCompat torchlens.types.SpecCompat removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
SiteTable torchlens.types.SiteTable removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
TargetManifestDiff torchlens.types.TargetManifestDiff removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
TensorLog torchlens.types.TensorLog removed (was: object alias via __getattr__; removed from __all__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
TensorSliceSpec torchlens.types.TensorSliceSpec removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
TorchLensPostfuncError torchlens.errors.TorchLensPostfuncError removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
TrainingModeConfigError torchlens.errors.TrainingModeConfigError removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
VisualizationOptions torchlens.options.VisualizationOptions removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
bwd_hook torchlens.bwd_hook kept top-level none test_api_surface.py
build_render_audit none (no longer public) removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
bundle torchlens.bundle kept top-level none test_api_surface.py
check_metadata_invariants torchlens.validation.check_metadata_invariants removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
check_spec_compat torchlens.validation.check_spec_compat removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
clamp torchlens.clamp kept top-level none test_api_surface.py
cleanup_tmp torchlens.io.cleanup_tmp removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
contains torchlens.contains kept top-level none test_api_surface.py
do Trace.do (a method; tl.do is gone) removed from the top level (interventions rename) removed 2026-10-31 test_api_surface.py
fastlog torchlens.recording renamed in round 2 (tl.fastlog is tl.recording) none test_api_surface.py
func torchlens.func kept top-level none test_api_surface.py
get_model_metadata torchlens.io.log_model_metadata removed (was: object alias via __getattr__; renamed) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
grad_scale torchlens.grad_scale kept top-level none test_api_surface.py
grad_zero torchlens.grad_zero kept top-level none test_api_surface.py
in_module torchlens.in_module kept top-level none test_api_surface.py
label torchlens.label kept top-level none test_api_surface.py
load torchlens.load kept top-level none test_api_surface.py
load_intervention_spec torchlens.io.load_intervention_spec removed (was: functools.wraps wrapper) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
list_logs torchlens.io.list_logs removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
trace torchlens.trace kept top-level none test_api_surface.py
log_model_metadata torchlens.io.log_model_metadata removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
mean_ablate torchlens.mean_ablate kept top-level none test_api_surface.py
module torchlens.module kept top-level none test_api_surface.py
noise torchlens.noise kept top-level none test_api_surface.py
preview_fastlog torchlens.fastlog.preview removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
project_off torchlens.project_off kept top-level none test_api_surface.py
project_onto torchlens.project_onto kept top-level none test_api_surface.py
replay Trace.do(site, edit) removed (was a warning alias) removed 2026-08 (shim-removal pass) scripts/checks/deprecation_inventory.py
replay_from Trace.do(site, value) removed (was a warning alias) removed 2026-08 (shim-removal pass) scripts/checks/deprecation_inventory.py
rehydrate_nested torchlens.io.rehydrate_nested removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
render_lines_to_html none (no longer public) removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
rerun torchlens.run removed (was a warning alias) removed 2026-08 (shim-removal pass) scripts/checks/deprecation_inventory.py
reset_naming_counter torchlens.io.reset_naming_counter removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
resample_ablate torchlens.intervention.scramble_elements removed (renamed; no alias) none test_interv_honesty_rename.py
resolve_sites torchlens.validation.resolve_sites removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
save torchlens.save kept top-level none test_api_surface.py
save_intervention torchlens.io.save_intervention removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
scale torchlens.scale kept top-level none test_api_surface.py
draw_backward torchlens.visualization.draw_backward removed (was: functools.wraps compatibility wrapper) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
show_model_graph torchlens.visualization.show_model_graph removed (was: functools.wraps wrapper) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
splice_module torchlens.splice_module kept top-level none test_api_surface.py
steer torchlens.steer kept top-level none test_api_surface.py
summary torchlens.visualization.summary removed (was: functools.wraps wrapper) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
suppress_mutate_warnings torchlens.errors.quiet() removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
swap_with torchlens.intervention.helpers.swap_with removed from the top level (interventions rename) removed 2026-10-31 test_api_surface.py
unwrap_torch torchlens.backends.torch.wrappers.unwrap_torch removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
validate_batch_of_models_and_inputs none: call torchlens.validate(model, x) per model (the submodule function was removed too) removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
validate_backward_pass torchlens.validation.validate_backward_pass removed (was: functools.wraps wrapper) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
validate_forward_pass torchlens.validation.validate_forward_pass removed (was: functools.wraps wrapper) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
validate_saved_activations torchlens.validate(scope="saved") removed (was: paper-era compatibility shim) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
where torchlens.where kept top-level none test_api_surface.py
wrap_torch torchlens.backends.torch.wrappers.wrap_torch removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
wrapped torchlens.backends.torch.wrappers.wrapped removed (was: object alias via __getattr__) removed 2026-08 (shim-removal pass) test_api_surface_deprecation.py
zero_ablate torchlens.zero_ablate kept top-level none test_api_surface.py
peek torchlens.pluck removed (was a warning alias) removed 2026-08 (shim-removal pass) scripts/checks/deprecation_inventory.py
extract torchlens.extract implemented top-level helper none test_api_surface.py
batched_extract torchlens.extract_dataset removed (was a warning alias) removed 2026-08 (shim-removal pass) scripts/checks/deprecation_inventory.py
validate torchlens.validate implemented top-level helper none test_api_surface.py
tap torchlens.observers.tap implemented observer helper none test_api_surface.py
record_span torchlens.observers.span removed (was a warning alias) removed 2026-08 (shim-removal pass) scripts/checks/deprecation_inventory.py

Phase 1b: option classes + canonical vocabulary

Grouped options are now available under torchlens.options. Individual kwargs continue to work for the migration window, but option objects are the preferred style for new code.

For selective activation capture, the unified predicate surface is now preferred: tl.trace(model, x, save=tl.func("relu")) returns a full Trace, while tl.record(model, x, save=tl.func("relu")) returns a sparse Recording. The old record(keep_op=...) / record(keep_module=...) alias kwargs are removed. Use storage=tl.to_disk(path) to stream predicate-selected payloads to disk.

Backend selection is now explicit when needed: tl.trace(..., backend=None) preserves torch eager default plus MLX module auto-routing, while backend="torch" forces the torch backend and fails early if the model/input does not match. Public backend metadata is exposed on Trace.backend, Trace.module_identity_mode, Trace.param_source, and neutral record fields such as dtype_ref, device_ref, backend_address, and resolver_status. tl.record() remains torch-only in backend v1.

Entry point Old kwarg New option-class field / canonical kwarg
trace layers_to_save Use save=... for predicates, label lists, module addresses, and final-label two-pass selection.
trace keep_unsaved_layers No direct equivalent: trace metadata is retained for all operations; use save=... to control saved payloads.
trace output_device capture=CaptureOptions(output_device=...)
trace save_function_args capture=CaptureOptions(save_args=...)
trace save_gradients, gradients_to_save, save_grads_to, keep_grads_in_memory save_grads=... and storage=tl.to_disk(...)
trace random_seed, detect_loops capture=CaptureOptions(seed=..., recurrence_detection=...)
trace mark_input_output_distances capture=CaptureOptions(compute_input_output_distances=...)
trace activation_postfunc capture=CaptureOptions(activation_transform=...)
trace gradient_postfunc capture=CaptureOptions(grad_transform=...)
trace save_raw_activation, save_raw_gradient capture=CaptureOptions(save_raw_activations=..., save_raw_gradients=...)
trace save_activations_to, activation_sink storage=StorageOptions(path=..., on_save=...)
show_model_graph / draw_backward vis_mode rolled or VisualizationOptions(rolled=...)
show_model_graph / draw_backward vis_nesting_depth depth or VisualizationOptions(depth=...)
show_model_graph / draw_backward vis_renderer renderer or VisualizationOptions(renderer=...)
show_model_graph / draw_backward vis_node_placement layout or VisualizationOptions(layout=...)
show_model_graph / draw_backward vis_node_mode node_style or VisualizationOptions(node_style=...)
tl.viz.bundle_diff vis_save_only open_viewer (True opens a viewer; the default never does)
Trace.replay, Trace.replay_from, Trace.rerun strict, hooks, append replay=ReplayOptions(strict=..., append=...); hooks became a mapping of sites to edits on Trace.do
Trace.do engine, confirm_mutation, strict intervention=InterventionOptions(engine=..., strict=...); confirm_mutation has no replacement: edit a fork() for a quiet copy, or wrap intentional in-place edits in torchlens.errors.quiet()

Before:

log = tl.trace(
    model,
    x,
    layers_to_save=["fc1"],
    activation_postfunc=lambda t: t.detach().cpu(),
    vis_mode="rolled",
    vis_nesting_depth=2,
)

After:

log = tl.trace(
    model,
    x,
    capture=tl.options.CaptureOptions(activation_transform=lambda t: t.detach().cpu()), save=tl.func("linear"),
)
log.draw(rolled=True, depth=2)

Forward validation:

# Before
import torchlens as tl
ok = tl.validate_forward_pass(model, x, None, 42)

# After
from torchlens.validation import validate_forward_pass
ok = validate_forward_pass(model, x, None, 42)

Consolidated validation accepts backend=None and dispatches through the same backend registry as capture. Supported backend/scope pairs return real bools; unsupported capabilities raise typed backend errors instead of silently skipping.

Backward validation:

# Before
ok = tl.validate_backward_pass(model, x, None, loss_fn)

# After
from torchlens.validation import validate_backward_pass
ok = validate_backward_pass(model, x, None, loss_fn)

Saved-activation validation:

# Before
ok = tl.validate_saved_activations(model, x)

# After
ok = tl.validate(model, x, scope="saved")

Summary:

# Before
text = tl.summary(model, x)

# After (tl.summary stays the one-call front door)
text = tl.summary(model, x)

Forward graph:

# Before
tl.show_model_graph(model, x, vis_outpath="graph", vis_save_only=True)

# After
trace = tl.trace(model, x)
trace.draw(path="graph")

Backward graph:

# Before
dot = tl.draw_backward(trace, vis_outpath="backward")

# After
loss = trace[trace.output_layers[0]].out.sum()
trace.backward(loss)
dot = trace.draw(graph="backward", path="backward")

Intervention spec load:

# Before
spec = tl.load_intervention_spec("run.tlspec")

# After
# `run.tlspec` is a placeholder for a file previously written by your application.
spec = tl.load("run.tlspec")
# or
from torchlens.io import load_intervention_spec
spec = load_intervention_spec("run.tlspec")

Phase 1c: exception taxonomy

TorchLens-specific failures now share a compact domain taxonomy under torchlens.errors. Existing exception names remain available for one minor cycle so current except OldExceptionName: blocks keep working.

import torchlens as tl
from torchlens import errors

try:
    log = tl.trace(model, x)
except errors.ConfigurationError:
    handle_bad_options()
except errors.CompatibilityError:
    handle_unsupported_model_or_storage()
except errors.CaptureError:
    handle_capture_failure()
except errors.ValidationError:
    handle_validation_failure()
except errors.InterventionError:
    handle_intervention_failure()

Every TorchLens exception and warning exposes the structured payload fields file_path, line_no, affected_sites, and severity.

A row whose status reads "removed" names a class that no longer exists under any import path; catch or subclass the replacement class it names instead.

Old import path New base Status
torchlens._errors.TorchLensPostfuncError torchlens.errors.CaptureError removed; use torchlens.errors.UserTransformError (subclass)
torchlens._io.TorchLensIOError torchlens.errors.CompatibilityError removed; use torchlens.errors.ArtifactError (subclass)
torchlens._robustness.UnsupportedTensorVariantError torchlens.errors.CompatibilityError subclass
torchlens._training_validation.TrainingModeConfigError torchlens.errors.ConfigurationError subclass
torchlens.fastlog.exceptions.RecordingConfigError torchlens.errors.ConfigurationError subclass
torchlens.fastlog.exceptions.RecorderStateError torchlens.errors.CaptureError subclass
torchlens.fastlog.exceptions.RecoveryError torchlens.errors.CaptureError subclass
torchlens.fastlog.exceptions.BundleNotFinalizedError torchlens.errors.CaptureError subclass
torchlens.fastlog.exceptions.RecordContextFieldError torchlens.errors.ConfigurationError subclass
torchlens.fastlog.exceptions.PredicateError torchlens.errors.CaptureError subclass
torchlens.intervention.errors.TorchLensInterventionError torchlens.errors.InterventionError subclass
torchlens.intervention.errors.TorchLensInterventionWarning torchlens.errors.TorchLensWarning removed; use torchlens.errors.InterventionWarning (subclass)
torchlens.intervention.errors.InterventionReadyConflictError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.DirectActivationWriteWarning torchlens.errors.TorchLensWarning subclass
torchlens.intervention.errors.MutateInPlaceWarning torchlens.errors.TorchLensWarning removed; use torchlens.errors.TraceMutationWarning (subclass)
torchlens.intervention.errors.DirectWriteIgnoredWarning torchlens.errors.TorchLensWarning subclass
torchlens.intervention.errors.InterventionAuditWarning torchlens.errors.TorchLensWarning subclass
torchlens.intervention.errors.MultiMatchWarning torchlens.errors.TorchLensWarning subclass
torchlens.intervention.errors.ReplayPreconditionError torchlens.errors.InterventionError subclass
torchlens.intervention.errors.OpaqueCallableInExecutableSaveError torchlens.errors.ConfigurationError removed; use torchlens.errors.OpaqueCallableError (subclass)
torchlens.intervention.errors.SpecPortabilityError torchlens.errors.ConfigurationError alias of OpaqueCallableError
torchlens.intervention.errors.DirectWriteInExecutableSaveError torchlens.errors.ConfigurationError removed; use torchlens.errors.DirectWriteSaveError (subclass)
torchlens.intervention.errors.GraphShapeMismatchError torchlens.errors.ValidationError subclass
torchlens.intervention.errors.ControlFlowDivergenceWarning torchlens.errors.TorchLensWarning subclass
torchlens.intervention.errors.ControlFlowDivergenceError torchlens.errors.ValidationError subclass
torchlens.intervention.errors.EngineDispatchError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.ModelMismatchError torchlens.errors.CompatibilityError subclass
torchlens.intervention.errors.AppendMismatchError torchlens.errors.ValidationError subclass
torchlens.intervention.errors.AppendBatchDependenceError torchlens.errors.ValidationError subclass
torchlens.intervention.errors.BatchNormTrainModeWarning torchlens.errors.TorchLensWarning subclass
torchlens.intervention.errors.SpecMutationError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.SiteResolutionError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.SiteAmbiguityError torchlens.errors.ConfigurationError removed; use torchlens.errors.AmbiguousSiteError (subclass)
torchlens.intervention.errors.RecursiveTracingError torchlens.errors.CaptureError subclass
torchlens.intervention.errors.AxisAmbiguityError torchlens.errors.ConfigurationError removed; use torchlens.errors.AmbiguousAxisError (subclass)
torchlens.intervention.errors.SpliceModuleDtypeError torchlens.errors.CompatibilityError subclass
torchlens.intervention.errors.SpliceModuleDeviceError torchlens.errors.CompatibilityError subclass
torchlens.intervention.errors.HookSignatureError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.HookValueError torchlens.errors.InterventionError subclass
torchlens.intervention.errors.HookSiteCoverageError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.LiveModeLabelError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.BundleMemberError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.BundleRelationshipError torchlens.errors.ValidationError removed; use torchlens.errors.BundleComparisonError (subclass)
torchlens.intervention.errors.BaselineUndeterminedError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.NoParentError torchlens.errors.ConfigurationError subclass
torchlens.intervention.errors.DeadParentError torchlens.errors.ConfigurationError subclass
torchlens.validation.invariants.MetadataInvariantError torchlens.errors.ValidationError subclass

The options restructure removes CaptureOptions.layers_to_save: pass the same selection as save=... to tl.trace or tl.record. For tl.trace, omitting save retains all payloads; explicit save=None retains metadata only. Helpers that forwarded None to request all payloads must use save="all". CaptureOptions.save_preview is removed; no backend implemented preview saving. CaptureOptions.module_filter and tl.Trace(module_filter=) are removed: compose the predicate into save= (a selector such as tl.func("conv2d") & tl.in_module("encoder"), or a save predicate function that applies both conditions).

tl.record(..., return_output=True) is removed: tl.record always returns one object, and the model's return value is recording.output (for generate_kwargs=, generation.output). Rewrite out, rec = tl.record(..., return_output=True) as rec = tl.record(...) and out = rec.output. The output is held in memory only; a recording loaded from disk refuses with output_not_stored, and a failed partial recording refuses with output_forward_failed instead of returning None. tl.trace results expose the same trace.output.

Recording.keep_op_repr, Recording.save_grads_repr, Recording.activation_transform_repr and Recording.grad_transform_repr are removed: read the live values from recording.options (a tl.types.RecordingSettings), for example recording.options.keep_op. Recording(...) has no public constructor; tl.record and Recorder build it.