# Python API

Source: https://docs.surogate.ai/engine/reference/python-api/

Surogate's main Python API lives in the `surogate._surogate` extension module, built with nanobind. Use it when you want to drive training from your own Python code instead of the [CLI](/engine/reference/cli/).

## Importing

```python
from surogate._surogate import (
    DataLoader,
    OptimizerConfig,
    PretrainedConfig,
    RuntimeOptions,
    SurogateTrainer,
)
```

## Trainer lifecycle (high level)

A typical run looks like this:

1. Build a `PretrainedConfig` (model architecture) and `RuntimeOptions` (runtime, memory and precision).
2. Construct a `SurogateTrainer`.
3. Feed token batches with `step()` and run optimizer updates with `update_with_config()`.
4. Save checkpoints with `save_checkpoint()`.

### Shapes and dtypes

`SurogateTrainer.step()` expects NumPy arrays:

- `inputs`: `int32` shaped `[batch_size * world_size, seq_length]`
- `targets`: `int32` shaped `[batch_size * world_size, seq_length]`

## Useful entry points

- `SurogateTrainer.from_pretrained(...)`: create a trainer from pretrained weights and config (see the docstring in the stubs)
- `SurogateTrainer.import_weights(path)`: import weights from a Hugging Face safetensors file
- `SurogateTrainer.export_model(path)`: export full model weights
- `SurogateTrainer.export_adapter(path, base_model_path=...)`: export LoRA adapters (PEFT-compatible)
- `SurogateTrainer.step_with_kd(...)` / `SurogateTrainer.get_kd_loss()`: knowledge-distillation micro-step with a teacher top-K signal, and the resulting KD metric (see [Knowledge Distillation](/engine/guides/distillation/))
- `SurogateTrainer.get_allocator_info(gpu_id=0)`: allocator stats, handy for memory debugging

## Where to look next

The generated typing stubs document the full API:

- `surogate/_surogate.pyi`

---

## See also

- [CLI reference](/engine/reference/cli/): the same training workflows driven from YAML configs
- [Config reference](/engine/reference/config/): every config option with its default
- [Back to docs index](/engine/)
