# Training a projector

> Train one task-specific projector with XTuner while the encoder and the language model stay frozen.

---

LLMS index: [llms.txt](/Sage-SciPerception/llms.txt)

---

[TrainKit](https://github.com/InternLM/Sage-SciPerception/blob/main/trainkit/README.md) trains a scientific projector with [XTuner](https://github.com/InternLM/xtuner). XTuner owns the trainer, FSDP, packing, the scheduler, the losses and the optimizer; TrainKit adds the projector, the prompt and supervision mask, payload injection into the packed sequence, and an export that the inference example and [EvalKit](/docs/guides/evaluation/) read unchanged.

TrainKit covers all nine published `atom` projector modalities through `scip-train preflight` (`neu06-preflight` remains available as a backward-compatible alias) and [`recipes/projector_sft.py`](https://github.com/InternLM/Sage-SciPerception/blob/main/trainkit/recipes/projector_sft.py), which support optional `discrete`, `side`, `readout`, `task_head`, `output_scale` and `depth` components as well as multi-object and `atom_numbering` prompts. [`recipes/neu06_projector.py`](https://github.com/InternLM/Sage-SciPerception/blob/main/trainkit/recipes/neu06_projector.py) remains available for strict NEU06 validation.

The worked example below is [SciTS NEU06 sleep staging](/docs/tasks/eeg-neu06/), the first published recipe. Training samples are published at [`internlm/Sage-SciPerception-Training`](https://huggingface.co/datasets/internlm/Sage-SciPerception-Training).

> [!NOTE] Data preparation is out of scope
> Training reads a prepared `sage-training-data-v1` export — a manifest, the rows of a split, and the frozen encoder states a row's `array_index` names. Data preparation, signal processing and feature encoding are not part of the repository.

## Training data {#training-data}

Training splits are curated from each task's public scientific dataset and kept strictly disjoint from [EvalKit](/docs/guides/evaluation/)'s held-out evaluation sets by subject, protein target, crystal geometry or composition, or year. Rather than feeding raw signals or biological sequences into training, each export stores frozen scientific encoder outputs or spectral representations paired with multi-turn instruction rows; language supervision loss is applied only to assistant response tokens while projected scientific payload positions are masked out.

Runnable two-row exports for all nine verified modalities are published at [`internlm/Sage-SciPerception-Training`](https://huggingface.co/datasets/internlm/Sage-SciPerception-Training) using the `sage-training-data-v1` layout:

```text
<export>/
  dataset.json          # split index and manifest metadata
  train.jsonl           # conversations plus array_index pointers (no raw signals/sequences)
  features/
    features.json       # feature width, dtype, and frozen encoder metadata
    index.jsonl         # per-object metadata
    offsets.npy         # slice boundaries per object
    nodes.npy           # frozen encoder states or spectral patch arrays
    modality.npy        # optional discrete channel (3-way index for spectra/qm9s)
    side.npy            # optional scientific readout channel (rna/ncrna, protein-seq/mpbind)
```

| Modality / task | Sample path & HF config | Upstream dataset | Representation (`nodes.npy` / extra) |
| --- | --- | --- | --- |
| [DNA (`dna/splice`)](/docs/tasks/dna-splice/) | `samples/dna/splice` (`splice`) | MAGICS-LAB DNABERT-2 GUE (`splice/reconstructed`) | `[2, 3]` DNABERT-2 splice readout |
| [RNA (`rna/ncrna`)](/docs/tasks/rna-ncrna/) | `samples/rna/ncrna` (`ncrna`) | BEACON (`NoncodingRNAFamily`) | `[238, 640]` RNA-FM states + `side.npy` (`[2, 13]`) |
| [EEG (`eeg/neu06`)](/docs/tasks/eeg-neu06/) | `samples/eeg/neu06` (`neu06`) | PhysioNet Sleep-EDF (`sleep-cassette`) | `[68, 512]` REVE-Base patch states |
| [Crystal (`cif/jarvis`)](/docs/tasks/cif-jarvis/) | `samples/cif/jarvis` (`jarvis`) | JARVIS-DFT (`jdft-3d-20221212`) | `[22, 64]` CHGNet 0.3.0 atom states |
| [ECG (`ecg/phu01`)](/docs/tasks/ecg-phu01/) | `samples/ecg/phu01` (`phu01`) | PTB-XL (`1.0.3`) | `[720, 768]` ST-MEM patch states |
| [Spectra (`spectra/qm9s`)](/docs/tasks/spectra-qm9s/) | `samples/spectra/qm9s` (`qm9s`) | QM9S (`DiffSpectra`) | `[694, 50]` IR/Raman/UV patches + `modality.npy` |
| [Protein Struct (`protein-struct/psr`)](/docs/tasks/protein-struct-psr/) | `samples/protein-struct/psr` (`psr`) | ATOM3D PSR (`PSR-split-by-year`) | `[451, 384]` ProteinMPNN `v48-020` states |
| [Protein Seq (`protein-seq/mpbind`)](/docs/tasks/protein-seq-mpbind/) | `samples/protein-seq/mpbind` (`mpbind`) | MPBind BA1 | `[136, 1280]` ESM-2 states + `side.npy` (`[136, 2]`) |
| [XRD (`xrd/simxrd`)](/docs/tasks/xrd-simxrd/) | `samples/xrd/simxrd` (`simxrd`) | SimXRD-4M (`OLtrain`/`OLval`) | `[220, 512]` SimXRD residual CNN states |

Each two-row slice preserves real `array_index` and remapped offsets so you can run `scip-train preflight` end to end before preparing or requesting a full split (see [Full training data](https://huggingface.co/datasets/internlm/Sage-SciPerception-Training#full-training-data) or [open an issue](https://github.com/InternLM/Sage-SciPerception/issues/new)).

## Install {#install}

Python 3.12. XTuner is pinned to a commit and loaded from a source checkout, so the recipe does not depend on which XTuner is installed:

```bash
WORK=/path/to/work
XTUNER=$WORK/xtuner
git clone https://github.com/InternLM/xtuner.git "$XTUNER"
git -C "$XTUNER" checkout 79b9615c53e1b23e11d4dc37fd7eb66bbcefb3df
```

Install XTuner's own training dependencies at the same commit, following [its installation guide](https://github.com/InternLM/xtuner/blob/79b9615c53e1b23e11d4dc37fd7eb66bbcefb3df/docs/en/get_started/installation.md). The recipe trains a frozen MoE base with tilewise FP8, so that guide's *Install GroupedGEMM* and *Install AdaptiveGEMM* steps both apply, as does its flash-attn recommendation. Then add this repository's packages:

```bash
python -m pip install ./evalkit ./trainkit
```

CPU-only tests need neither XTuner nor GPUs:

```bash
uv run --no-project --with pytest --with ./evalkit --with ./trainkit --python 3.12 pytest trainkit/tests -q
```

## Inputs {#inputs}

The default run reads **no projector weights**: only the component's `config.json`, for the architecture, the output width and the prompt layout.

```bash
WORK=/path/to/work
GLM=$WORK/GLM-5.3-Flash-BF16
PROJECTOR=$WORK/component/projectors/glm-5.3-flash/eeg/neu06
DATA=$WORK/training-samples/samples/eeg/neu06

hf download zai-org/GLM-5.3-Flash-BF16 \
  --revision f9fed3bbc82291073373d67452e9f25317ef7577 --local-dir "$GLM"
hf download internlm/Sage-SciPerception projectors/glm-5.3-flash/eeg/neu06/config.json \
  --revision 7c228fc03394027fed19bda1ff26388394b0031a --local-dir "$WORK/component"
hf download internlm/Sage-SciPerception-Training --repo-type dataset \
  --include "samples/eeg/neu06/*" --local-dir "$WORK/training-samples"
```

Replace `$DATA` with your own export to train on your own data.

## Preflight {#preflight}

The preflight takes the recipe's own `DataloaderConfig` and asks XTuner for the dataset, the sampler and the collator, so its numbers describe the configuration the run will use. It needs no GPUs:

```bash
RUN=${RUN:-$WORK/runs/trial}
SCIP_PACK_MAX_LENGTH=${SCIP_PACK_MAX_LENGTH:-2048}
SCIP_GLOBAL_BATCH_SIZE=${SCIP_GLOBAL_BATCH_SIZE:-2}
SCIP_PACK_CHUNK_SIZE=${SCIP_PACK_CHUNK_SIZE:-1}
SCIP_TOTAL_EPOCH=${SCIP_TOTAL_EPOCH:-1}
PYTHONPATH="$XTUNER" scip-train preflight \
  --manifest "$DATA/dataset.json" --model "$GLM" \
  --projector-config "$PROJECTOR/config.json" --work-dir "$RUN/preflight" \
  --pack-max-length "$SCIP_PACK_MAX_LENGTH" --global-batch-size "$SCIP_GLOBAL_BATCH_SIZE" \
  --total-epoch "$SCIP_TOTAL_EPOCH" --sp-size 8 --pack-chunk-size "$SCIP_PACK_CHUNK_SIZE"
```

`sizing` reports the pack count, the steps per epoch, the total steps, the warmup steps and the dropped tail packs; the full report is written to `$RUN/preflight/preflight.json`. `scip-train neu06-preflight` is kept as an alias of `scip-train preflight` and takes the same arguments.

> [!IMPORTANT] Sizing constraints
> `global_batch_size` must be divisible by the data-parallel size, which is `world_size / sp_size` — sixteen GPUs at SP8 give DP2, so the global batch must be even and 2 is its minimum. `pack_max_length` must be divisible by `sp_size`. `round_up=False` drops the tail pack instead of padding, so each epoch consumes `packs // global_batch_size` packs: a split that packs into fewer packs than the global batch reaches zero steps.

Packing works on chunks of rows independently. The sample sets `--pack-chunk-size 1` so its two rows form two packs and fill one global batch. The full recipe uses a chunk size of 100000.

## Train {#train}

The full recipe was run on two eight-GPU nodes. The public sample was checked with XTuner's CPU preflight. Run the command once per node, with the same input paths and the preflight report available at `$RUN` on both nodes.

```bash
REPO=/path/to/Sage-SciPerception
RUN=${RUN:-$WORK/runs/trial}
export PYTHONPATH="$XTUNER"

export SCIP_MODEL_PATH="$GLM"
export SCIP_MANIFEST="$DATA/dataset.json"
export SCIP_PROJECTOR="$PROJECTOR"
export SCIP_PROJECTOR_SEED=20261129
read -r SCIP_PACK_MAX_LENGTH SCIP_GLOBAL_BATCH_SIZE SCIP_PACK_CHUNK_SIZE \
  SCIP_TOTAL_EPOCH SCIP_SP_SIZE SCIP_HF_INTERVAL < <(
  python -c 'import json,sys; s=json.load(open(sys.argv[1]))["sizing"]; print(*(s[k] for k in sys.argv[2:]))' \
    "$RUN/preflight/preflight.json" pack_max_length global_batch_size pack_chunk_size total_epoch sp_size steps_per_epoch
)
export SCIP_PACK_MAX_LENGTH SCIP_GLOBAL_BATCH_SIZE SCIP_PACK_CHUNK_SIZE SCIP_TOTAL_EPOCH SCIP_SP_SIZE SCIP_HF_INTERVAL
export SCIP_EXPERIMENT=${SCIP_EXPERIMENT:-neu06-projector-trial}
export XTUNER_WORK_DIR="$RUN/work_dir"

python -m torch.distributed.run \
  --nnodes 2 --nproc_per_node 8 \
  --node_rank "${NODE_RANK:?set by your launcher}" \
  --master_addr "${MASTER_ADDR:?set to the rank-0 host}" \
  --master_port "${MASTER_PORT:?pick one free port, the same on both replicas}" \
  "$XTUNER/xtuner/v1/train/cli/sft.py" \
  --config "$REPO/trainkit/recipes/projector_sft.py"
```

`recipes/projector_sft.py` is the general recipe and serves every published modality; use `recipes/neu06_projector.py` instead when you want the strict NEU06 checks.

For the full data, set these values in your training shell, then rerun the preflight and train commands above:

```bash
DATA=/path/to/training-export
RUN=$WORK/runs/full
SCIP_PACK_MAX_LENGTH=16384
SCIP_GLOBAL_BATCH_SIZE=2
SCIP_PACK_CHUNK_SIZE=100000
SCIP_EXPERIMENT=neu06-projector-muon-8e-6
```

The recipe is scaled from a GLM multimodal SFT setup: SP8/EP8 with the deepep dispatcher, tilewise FP8 GEMM, `torch.compile`, the NoPE-MLA backends, chunked main CE (1024, token reduction), seven shared MTP depths at 0.1, Muon (lr 8e-6, `weight_decay` 0.1, `swap_optimizer`), constant LR after a 10% warmup, one epoch. The pack length and global batch come from the preflight. `SCIP_LR` is the only intended sweep knob and is written into every export.

## Export and warm start {#export}

Each saved step writes `projector.safetensors` and a `config.json` whose `training` block records the learning rate, the sizing, the initialization and its seed, the manifest revision, the `dataset.json` and `features.json` the run read, and the encoder versions those files carry. Score an export with the [evaluation guide](/docs/guides/evaluation/).

To continue from a published projector instead of a fresh initialization, download its weights next to the `config.json` above and name the mode:

```bash
hf download internlm/Sage-SciPerception projectors/glm-5.3-flash/eeg/neu06/projector.safetensors \
  --revision 7c228fc03394027fed19bda1ff26388394b0031a --local-dir "$WORK/component"

export SCIP_PROJECTOR_INIT=warm-start
export SCIP_PROJECTOR_SHA256=3abbf3868cc6977b4a062bdd8938c045b65182a1b094e9cb3a2029394cf00f7e
unset SCIP_PROJECTOR_SEED
```

`SCIP_PROJECTOR_SHA256` is optional and is checked against the file about to be loaded; the value above is the one the component lists on Hugging Face.
