API Reference

Reference for the public classes and methods in ARC 5.2.0. Controller is the recommended entry point. The legacy APIs further down are still supported.

Controller

The single canonical entry point. It combines NaN/Inf, loss-explosion, weight-health, gradient, Lyapunov, and trend detection into one recovery loop, with snapshots copied to host memory on a background thread.

arc.core.controller.py
class Controller(
    model: nn.Module,
    optimizer: torch.optim.Optimizer,
    scheduler: Optional[Any] = None,
    config: Optional[ControllerConfig] = None,
    verbose: Optional[bool] = None,
    scaler: Optional[torch.amp.GradScaler] = None,
)

Pass scaler for fp16 training: ARC unscales the gradients and checks them at true scale. Under DDP every rank must create its controller the same way. FSDP and DTensor models raise an error.

Methods

MethodReturnsDescription
step(loss=None)StepActionMain entry point. Call after loss.backward() and before optimizer.step(). With None, the loss checks are skipped and everything else runs
post_backward()StepActionGradient-only NaN/Inf check. Redundant if you call step() after backward()
get_stats()dictStep count, rollbacks, skips, detected, confirmed, and pending failures, recovery rate, LR, stability, snapshot info
summary()strPrints and returns an end-of-training report
log_to_wandb(step=None)NoneLogs ARC metrics to Weights & Biases (no-op without wandb)
export_recovery_ledger(path=None)strJSON audit trail of every intervention. Written to path if given
verify_ledger_integrity()boolVerifies the ledger's hash chain (SHA-256, or HMAC-SHA256 with ledger_key)
reliability_roi_report(path=None)strWork lost this run and, with baseline_checkpoint_interval set, GPU-hours, dollars, and kg CO2 saved
save_checkpoint(path)NoneAtomic durable checkpoint of model, optimizer, scheduler, scaler, RNG, and ARC state. Loads with weights_only=True
load_checkpoint(path)intRestores a save_checkpoint file and returns the step to resume from
state_dict() / load_state_dict(state)dict / NoneARC's own state as plain Python values, for your own checkpoint format
close()NoneDetaches ARC's optimizer hooks and stops the snapshot thread

Attributes

AttributeTypeDescription
unrecoverableboolSticky. Set once ARC decides the fault is outside the model
total_rollbacks, total_skipsintIntervention counters
failures_detected, failures_recoveredintDetection counter, and failures confirmed recovered after recovery_confirm_steps healthy steps
intervention_loglist[dict]Hash-chained ledger entries

ControllerConfig

A dataclass. All fields are optional. See Defaults for the full table.

GroupFields
Checkpointingcheckpoint_frequency, max_checkpoints, cpu_offload, async_checkpoint, adaptive_frequency, min_checkpoint_frequency, max_checkpoint_frequency
Detectionloss_explosion_threshold, loss_spike_factor, gradient_explosion_threshold, auto_calibrate, calibration_steps, gradient_accumulation_steps, external_grad_scaler
Signalsenable_lyapunov, enable_trend, enable_gradient_monitoring, enable_weight_health, trend_window, trend_min_samples, lyapunov_window, lyapunov_sample_ratio, lyapunov_check_frequency
Recoverylr_reduction_factor, max_lr_reductions, lr_recovery_steps, recovery_confirm_steps, gradient_clip_norm, enable_baseline_clipping (False), max_consecutive_rollbacks, max_persistent_failures, skip_ahead_steps, weight_perturbation_scale
Weight healthweight_health_check_frequency, weight_sparsity_threshold, weight_magnitude_collapse_threshold
Cost and tagginggpu_count, gpu_hourly_cost, gpu_power_watts, carbon_intensity_kg_per_kwh, baseline_checkpoint_interval, team, project
Logging and ledgerverbose, log_interventions, ledger_key

StepAction and HealthStatus

FieldTypeDescription
stepintController step count
statusHealthStatusHEALTHY, WARNING, or FAILURE
should_skipboolSkip optimizer.step() for this batch
rolled_back, lr_reduced, gradients_clippedboolActions taken this step (gradients_clipped only with enable_baseline_clipping)
failure_typeOptional[str]nan_loss, loss_explosion, nan_weights, weight_sparsity_explosion (…), weight_magnitude_collapse (…), gradient_explosion, lyapunov_divergence, drift_detected, nan_gradients. The two weight-health types carry the measured value in parentheses
loss_value, health_scorefloatLoss and stability score (0 to 1)
lyapunov_exponent, training_phasefloat, strLatest Lyapunov estimate and phase
unrecoverableboolThe fault is in the data, loss, or precision, not the model
messagestrHuman-readable summary

LyapunovMonitor

from arc import LyapunovMonitor. Estimates the Lyapunov exponent online, with FFT oscillation detection. Each check reads a fixed per-tensor sample (10%, at most 500K values), so the cost stays flat on billion-parameter models.

MemberDescription
LyapunovMonitor(window=30, sample_ratio=0.1, ...)Constructor
update(model, lr=None) → LyapunovState. Pass lr to measure velocity per unit of learning rateexponent, phase (TrainingPhase), is_oscillating, dominant_frequency, confidence
exponent, is_divergent, is_warningProperties
reset(), get_diagnostics()State management

TrendDetector

from arc import TrendDetector. Fits a least-squares slope to loss, gradient-norm, and weight-norm windows to catch gradual drift.

MemberDescription
TrendDetector(window=50, min_samples=10, ...)Constructor
update(loss, grad_norm=None, weight_norm=None) → DriftReportseverity (DriftSeverity), per-signal slopes, n_signals_drifting, confidence, message
reset(), get_diagnostics()State management

Framework Callbacks

from arc.api.integrations import HuggingFaceCallback, LightningCallback. Both build an arc.Controller when training starts and call step(None) just before each optimizer step. A poisoned update is skipped by clearing the gradients, and the weights are rolled back.

MemberDescription
HuggingFaceCallback(config=None, enable_rollback=True, verbose=True, loss_threshold=None, gradient_threshold=None)For transformers.Trainer. Runs in on_pre_optimizer_step. Needs pip install "arc-training[hf]"
LightningCallback(config=None, enable_rollback=True, verbose=True, loss_threshold=None, gradient_threshold=None)For Lightning. Runs in on_before_optimizer_step and protects the first optimizer. Needs pip install "arc-training[lightning]"
controller, skipped_stepsThe underlying Controller and the number of updates skipped
protect_trainer(hf_trainer, **kwargs)In arc.api.bulletproof. Adds a HuggingFaceCallback to an existing trainer

AdaptiveCheckpointer

from arc.checkpointing import AdaptiveCheckpointer, AdaptiveCheckpointConfig, CheckpointStrategy

MemberDescription
AdaptiveCheckpointer(model, optimizer, config=None)Picks FULL_CPU, QUANTIZED_FP16, QUANTIZED_INT8, INCREMENTAL_DELTA, STREAMING_DISK, or SHARDED from available memory
save(step=None) → CheckpointMetadataSave with the current strategy
restore(checkpoint_idx=-1) → intRestore, verifying hash and HMAC when signing is on
get_stats()Strategy, sizes, compression ratio
AdaptiveCheckpointConfig(sign_checkpoints=False, signing_key=None, quantize_optimizer=False, allow_unsafe_load=False, ...)SHA-256 and HMAC integrity on every strategy. Optimizer state is never quantized unless asked. Disk loads use weights_only=True unless allow_unsafe_load
verify_recoverability(checkpointer, model_factory, optimizer_factory, sample_input, tolerance=1e-4)In arc.checkpointing.dr_drill. Returns RecoveryDrillReport(passed, max_abs_diff, tolerance, detail)
safe_torch_load(path, map_location=None, allow_unsafe=False)In arc._serialization. torch.load with weights_only=True. allow_unsafe=True warns and unpickles; use it only for files you produced

PolicyEngine

from arc.prediction.policy import PolicyEngine, RemediationPolicy

MemberDescription
RemediationPolicy(name, min_overall_risk=0.0, min_confidence=0.0, failure_mode=None, actions=[], dry_run=True)One rule. dry_run=True is the approval gate
RemediationPolicy.from_dict(data)Build a policy from a dict. Raises ValueError naming the bad field
PolicyEngine(policies, notifiers=None)notifiers maps action name to a callable
PolicyEngine.from_config(path, notifiers=None)Load policies from a JSON list
evaluate(prediction) → list[PolicyDecision]Match a FailurePrediction against every policy. A prediction with risk_level="unknown" never matches
export_log(path=None) → strJSON decision log

AlertRouter

from arc.api.alerting import AlertRouter, Alert, Severity

MemberDescription
SeverityINFO, WARNING, CRITICAL
Alert(severity, title, message, dedup_key, impact=None)One alert
AlertRouter(channels, dedup_window_seconds=300.0)channels maps Severity to a list of callables
route(alert) → boolSends to every channel at or below the alert's severity. Returns False if suppressed as a duplicate

EnterpriseReport

from arc.api.enterprise_report import EnterpriseReport

MemberDescription
EnterpriseReport(controller, policy_engine=None, alert_router=None)Collects the ledger, ROI report, policy decisions, and alerts
to_dict(), to_html()JSON-ready dict, or a self-contained HTML page with inline SVG
save(json_path=None, html_path=None)Write either or both

Evaluation

Function / ClassModuleDescription
RunComparator(rollback_rate_tolerance=0.5, stability_slope_tolerance=0.01)arc.evaluation.run_comparisoncompare(baseline, current) and compare_files(a, b) → ComparisonReport (has_regression, findings)
compute_reliability_metrics(intervention_log)arc.evaluation.reliability_metricsReliabilityMetrics: total failures and recoveries, recovery rate overall and by reason, mean and median steps lost per rollback, mean steps and seconds between failures. Recoveries count only confirmed ones
aggregate_ledgers(ledgers), aggregate_ledger_files(glob)arc.evaluation.chargebackGPU-hours and dollars saved per team/project. Runs without a savings baseline are counted in runs_with_unknown_savings

Silent Data Corruption

from arc.security.sdc_detection import CrossReplicaGradientCheck, DeterministicReplayVerifier and from arc.security.reproducibility import ReproducibilityTracker

MemberDescription
CrossReplicaGradientCheck(relative_deviation_threshold=3.0)check({rank: grad}) → SDCAlert. Median-consensus outlier ranks (needs at least 3 ranks)
DeterministicReplayVerifier(tolerance=1e-5)verify(model, inputs, reference_output=None) → SDCAlert
ReproducibilityTracker(verifier=None, check_every_n_calls=1)maybe_check(model, inputs), report() → ReproducibilityReport

HealthBaseline

from arc.security.health_baseline import HealthBaseline

MemberDescription
HealthBaseline(zscore_threshold=3.0)Learns per-metric mean and std from past ledgers
add_run(ledger), check(ledger) → BaselineReportis_anomalous, deviations. Needs at least 2 prior runs per metric
save(path), HealthBaseline.load(path)Persist as JSON

StragglerDetector

from arc.distributed.straggler_detection import StragglerDetector

MemberDescription
StragglerDetector(window=20, zscore_threshold=4.0, min_consecutive_flags=3)MAD-based per-rank step-time outliers
record_step({rank: seconds}) → StragglerReporthas_straggler, straggler_ranks, per_rank_zscore. Ranks that stop reporting are pruned

RLStabilityMonitor

from arc.signals.rl_stability import RLStabilityMonitor

MemberDescription
RLStabilityMonitor(window=50, kl_threshold=0.1, entropy_floor=0.01, entropy_slope_threshold=-1e-3, advantage_zscore_threshold=5.0, reward_hacking_slope_gap=1e-4)Constructor
update(kl=None, entropy=None, reward=None, true_objective=None, advantage=None) → RLStabilityReportkl_blowup, entropy_collapse, reward_hacking, advantage_explosion, is_healthy, messages

RolloutHealthMonitor

from arc.signals.rollout_health import RolloutHealthMonitor

MemberDescription
RolloutHealthMonitor(ngram_n=3, repetition_threshold=0.3, unique_ratio_threshold=0.3, length_window=50, length_zscore_threshold=4.0)Constructor
check_batch(sequences) → RolloutHealthReportmode_collapse, high_repetition, format_drift, is_healthy, messages

Arc (legacy)

The original epoch-level monitoring controller, built on signal collectors and the failure predictor.

arc.api.callback.py
class Arc(
    config: Optional[Config] = None,
    model_path: Optional[str] = None,
    auto_intervene: bool = False,
    verbose: bool = True,
)

Methods

MethodReturnsDescription
attach(model, optimizer)ArcAttach ARC to a model and optimizer
detach()NoneRemove all hooks and detach
on_batch_end(loss, step)NoneCall after each batch to record loss
on_epoch_end(epoch, val_loss, train_loss)FailurePredictionCall at epoch end. Returns the failure prediction
get_report()strText report of training health
save_state(path) / load_state(path)NonePersist and restore internal state
reset()NoneReset all internal state
overhead_percentagefloatProperty: current ARC overhead as % of training time
Context Manager

Arc supports the context manager protocol. Use with Arc(...) as arc: for automatic cleanup.

ArcV2 (legacy)

Extends Arc with automatic configuration by model size, EWC continual learning, conformal uncertainty, and adversarial detection.

arc.api.v2.py
arc = ArcV2.auto(
    model,
    optimizer,
    task_type="classification",
    safety_level="standard",
)
MethodReturnsDescription
auto(model, optimizer, task_type, safety_level)ArcV2Class method to auto-initialize
step(loss, x=None, y=None)dictRecords one training step. Does not call backward() or apply the EWC penalty
end_epoch(epoch, val_loss=None, train_loss=None)dictEpoch-level prediction and interventions
begin_task(task_id)NoneStarts a new continual-learning task (EWC)
consolidate_task(dataloader, task_id=None)NoneComputes Fisher information for EWC
get_ewc_loss()TensorEWC penalty to add to your loss before backward()
calibrate_uncertainty(...) / predict_with_uncertainty(...)Conformal prediction helpers
fit_adversarial_detector(...) / check_adversarial(x)Adversarial detection helpers
save(path) / load(path, model=None)NonePersist and restore state, including EWC Fisher matrices

ArcCallback (legacy)

PyTorch Lightning callback built on Arc. For Hugging Face Trainer, use arc.api.integrations.HuggingFaceCallback or arc.api.bulletproof.protect_trainer(trainer).

usage.py
from arc import ArcCallback

trainer = pl.Trainer(callbacks=[ArcCallback(
    auto_intervene=True,
    verbose=True,
)])

Config (legacy)

FieldTypeDefault
signalSignalConfigDefault signal settings
featureFeatureConfigWindow size 10, min history 3
predictionPredictionConfigGRU hidden 64, 2 layers
thresholdsFailureThresholdsStandard thresholds
overheadOverheadConfig5% max overhead
devicestr"auto"

Class Methods

MethodDescription
Config.low_overhead()Production preset: 5% sampling, no curvature, 2% max overhead
Config.high_accuracy()Research preset: 30% sampling, curvature proxy, spectral features
Config.from_json(str)Deserialize from a JSON string
Config.from_dict(dict)Create from a dictionary

SignalConfig

FieldTypeDefaultDescription
collect_every_n_stepsint1Collection frequency
activation_sample_ratiofloat0.1Fraction of activations to sample
compute_gradient_entropyboolTrueCompute the gradient entropy metric
compute_curvature_proxyboolFalseEnable Hessian-vector product estimation
track_effective_rankboolTrueTrack the effective rank of weight matrices

PredictionConfig

FieldTypeDefault
temporal_hidden_sizeint64
num_gru_layersint2
mc_dropout_samplesint20
high_risk_thresholdfloat0.7
medium_risk_thresholdfloat0.4

FailureThresholds

FieldTypeDefault
loss_explosion_factorfloat10.0
loss_nan_detectionboolTrue
vanishing_grad_thresholdfloat1e-7
exploding_grad_thresholdfloat1e4
activation_similarity_thresholdfloat0.95
effective_rank_collapse_ratiofloat0.3
overfit_gap_thresholdfloat0.5

Signal Collectors

CollectorSignals
GradientCollectorGradient norms, entropy, histogram
ActivationCollectorActivation stats, similarity, effective rank
WeightCollectorWeight norms, NaN/Inf check, variance
OptimizerCollectorOptimizer state integrity, momentum norms
LossCollectorLoss trajectory, EMA, acceleration
CurvatureCollectorHessian-vector products (optional)

PINNStabilizer

MethodDescription
__init__(model, n_loss_terms=3, use_curriculum=True, use_lyapunov=True)Initialize with the model and number of loss components
get_stabilized_loss(losses)Adaptively weighted combined loss
stabilize_step()Apply gradient stabilization
update(epoch, loss)Update internal state for curriculum scheduling. Returns diagnostics

ConformalPredictor

MethodDescription
__init__(model, alpha=0.1, score_function="aps")Initialize with the model and significance level
calibrate(loader, use_venn_abers=True)Calibrate on held-out data
predict(x)PredictionSet with prediction, confidence, set_members, set_size, coverage_target

AdversarialDetector

MethodDescription
__init__(model, detection_threshold=0.8, methods=None)Methods default to Mahalanobis, LID, entropy, and gradient
fit(clean_loader, n_samples=1000)Fit the detector on the clean data distribution
detect(x)AdversarialAlert with is_adversarial, confidence, detection_method

ElasticWeightConsolidation

from arc import ElasticWeightConsolidation

MethodDescription
__init__(model, lambda_ewc=1000.0, fisher_estimation="empirical", online=False, gamma=0.9)Initialize with the model and EWC strength
consolidate_task(task_id, dataloader, criterion=None, n_samples=None)Compute Fisher information and store the optimal parameters
compute_penalty()EWC penalty loss
get_importance_scores(), n_tasksPer-parameter importance and the number of consolidated tasks
state_dict() / load_state_dict(state, device="cpu")Persist and restore

BulletproofTrainer

Combines OOM recovery, numeric rollback, silent-failure detection, and hardware-fault handling. Faults it cannot fix in-process (a lost CUDA context, a dead rank) are reported as failures with advice to restart and resume. Presets: BulletproofConfig.for_llm(), for_gan(), for_vae(), minimal_overhead().

bulletproof.py
from arc import BulletproofTrainer, BulletproofConfig

trainer = BulletproofTrainer(model, optimizer, BulletproofConfig.for_llm(),
                             scheduler=scheduler, scaler=scaler)

for epoch in range(num_epochs):
    for batch in train_loader:
        result = trainer.train_step(batch, forward_fn=lambda b: compute_loss(model, b))
    trainer.end_epoch(val_loss=evaluate(model))

print(trainer.get_stats())