Repository navigation
Releases
Releases · ViperEkura/AstrAI
v1.4.0
Highlights
- Online training: add PPO with a value-model critic and GAE, configurable DAPO controls, rollout weight versioning, cross-GPU replicas, and multi-process DDP rollout support.
- Distributed training: add plan-driven tensor parallelism and context parallelism for long sequences.
- Inference: reorganize the engine into frontend, core, and worker layers; add token-budget chunked prefill, serving overlap, and lower-overhead decode scheduling.
- Models and checkpoints: add Gated DeltaNet attention with CUDA kernels and end-to-end loading of hybrid Hugging Face text checkpoints.
- CUDA and optimization: expand FP8 training and quantized GEMM support, improve Muon Newton-Schulz kernels, and reduce cross-entropy and rollout memory use.
- Evaluation and packaging: add MBPP and HellaSwag evaluation, checkpoint watching and result collection, plus Linux and Windows CUDA wheel builds.
Fixes
- Keep online rollout samples consistent with the published policy version and save checkpoints after optimizer steps.
- Correct causality with two-dimensional padding masks and keep MoE expert routing consistent.
- Address CUDA kernel installation, FP8 scaling, and several training and inference correctness issues.
Compatibility notes
- The private
_C_symmetricextension has been consolidated into_C_newton_schulz. Code importing the old native module directly must update its import. - Inference and extension internals have been reorganized. Review custom integrations that import private module paths.
- The package requires Python 3.12 or newer and declares PyTorch 2.11.0. Release wheels are built with CUDA 13.0.
Thanks to all contributors, including the first-time contributors recognized in the GitHub comparison.
Full changelog: v1.3.13...v1.4.0
v1.3.13
Breaking
- Remove
GenerationRequestclass andgenerate_with_requestmethod - Change default attention backend priority from flash>cuda>torch to cuda>flash>torch
JsonlStore.load()requires explicittransform=for eager mode (auto-creation moved toDatasetFactory)- CUDA graph capture enabled by default at
Executorinit
Features
- CUDA graph capture for decode forward step (1.75-2.11x speedup)
attn_paged_decodekernelout_bufparameter for graph-safe outputsupports_graph()onAttentionBackendABC, overridden byCudaBackendASTR_BACKENDenv var for default backend override (cuda|flash|torch_native)timed()context manager (ASTRAI_TIMED=1) for per-phase wall-clock profiling- Backend
supports()static method on each backend class FlashAttnBackenddecode usesflash_attn_with_kvcachefor contiguous cache (1.40x vs torch_native)
Refactors
- Merge streaming/non-streaming generation into single
_generate(stream=bool) - Replace flash-attn double-checked locking with
@functools.lru_cache - Extract
_write_and_gather_kv()shared betweenTorchNative/FlashAttnbackends - Replace
isinstance(get_backend(), CudaBackend)withget_backend().supports_graph() - Add
_BindStatedataclass +_is_steady_increment()shared betweenExecutor/PagePool CudaBackend.supports()now includestorch.cuda.is_available()guard- Replace bare-tuple
_decode_cachewithDecodeSteadyStatedataclass - Break
JsonlStore→preprocessingcircular dependency (transform routing moved toDatasetFactory)
Fixes
FlashAttnBackenddtype guard in_backend_supports(was missing fp32 check)- Scheduler test fixture uses bf16 model instead of fp32 (avoids 3-step fallback)
test_default_backend_resolves_to_availablerenamed from misleading_torch_native
Docs
- Sync all documentation with current codebase (class diagrams, backend hierarchy, API references)
- Fix
python -m scripts.tools.server→ direct script call
v1.3.12
Changelog
v1.3.12
Features
- Mano optimizer: add
mano_adamw— manifold normalized optimizer with axis-rotating tangent projection, replacing Newton-Schulz iteration with cheaper normalization - Nora optimizer: add
nora_nadamw— normalized orthogonal row alignment for matrix weights paired with Nesterov AdamW - Gradient SNR metric: EMA-based gradient signal-to-noise ratio tracking (
grad_snr) added to default metrics - Grouped CLI options:
--helpnow renders options in 10 labeled sections (Paths & Setup, Training, Optimizer, LR Schedule, etc.) - AttentionBackend ABC: context-manager-based backend selection with
TorchNativeBackend(SDPA) andCudaBackend(kernel dispatch) - Fused CUDA rotary kernel: single-kernel rotary embedding (cos/sin lookup + rotation) with auto-dispatch (CUDA if available, else torch complex-multiply)
- Multi-dim mask support: attention kernels accept 2D/3D/4D masks with broadcasting
- torch.compile:
--compileCLI option for training (default/reduce-overhead/max-autotune) - YAML config:
--configflag for train CLI, CLI flags override YAML values - GPU-accelerated SVD:
--deviceflag for weight analysis eval, defaults to cuda - Rust DecodeStream: O(n) streaming decode replacing Python token-by-token loop
- Hierarchical logger:
setup_logging()withastrailogger namespace
Performance
- Decode cp.async pipeline: split-KV MMA kernels use true multi-stage
cp.async(wait_group<STAGES-1>), keeping STAGES-1 tile loads in flight (+31-40% decode throughput) - Split partials memset removal:
torch::emptyreplaces per-call zeros/full memset (2 kernels/layer/step eliminated) - BC=16 decode tile: higher occupancy for D=256 (spill eliminated, 248 regs, 0 spill)
- Paged MMA for page_size=1: decode path uses paged kernel with
req_to_tokenas page table - Scheduler/executor overhead: precompute
page_table/decode_maskper step (was per-layer), skip frequency penalty when all-zero, singleget_active_tasks()call - Rotary kernel: 6-9x faster than torch complex-multiply across decode/prefill shapes
- Eval batch sizes: increased default eval batch sizes +
max_seq_lenconfig
Fixes
- ManoAdamW AdamW: use
torch.optim.AdamW(fused)instead of customNAdamW, matching MuonAdamW for fair comparison - Paged decode stability: fix race condition in paged decode attention kernels
- Rotary grad guard: skip CUDA rotary kernel when
torch.is_grad_enabled(), ensuring autograd compatibility for training - FSDP fixes:
clip_grad_normcorrectness,unwrap_modelcollective op + None guard,reshard_after_forward=Falsedefault - FSDP ref/old model: broadcast
state_dictfor FSDP-wrapped ref/old models - Resume epoch: correct epoch computation on resume to avoid redoing completed epochs
- Metric logs: keep cumulative instead of segmental within each checkpoint
- ChatTemplate pickling:
__getstate__/__setstate__drops unpicklable Jinja2 closure for spawn multiprocessing
Refactoring
- Composite optimizer helpers: extract
composite_step/zero_grad/state_dict/refresh_param_groupstoastrai/optim/composite.py;OptimizerFactorymoved here to enable@registerdecorator in each optimizer module - Naming unification:
MuonMix→MuonAdamW, filemuon_mix.py→muon_adamw.py - KV cache: three-layer separation architecture (PagePool / KVCache / PrefixCache) with single-index access
- FSDP2 as default: replace
FullyShardedDataParallelwith per-modulefully_shard, removefsdp2CLI choice - Config system: migrate to Pydantic dataclasses with field/model validators
- Extension API: unify to blhd layout (
[batch, seq_len, n_heads, head_dim]) andis_causalinterface - Storage backend: remove H5 in favor of mmap bin (sole pre-tokenized storage)
- Factory pattern: simplify
BaseFactory, separateModelFactoryfromAutoModel
Build
- CUDA wheel matrix: parametrize CUDA version (cu128, cu130) for wheels and Docker
- .so output path: compiled kernels land in
astrai/extension/lib/(wasastrai/_ext/)
Docs
- Restructure to
docs/withguides/anddeveloper/subdirectories - Add
get-started.md,evaluation.md,distributed.md,internals.md,cuda_kernels.md - Document
mano_adamwandnora_nadamwoptimizer parameters inparams.md
v1.3.11
CUDA Kernels
- MMA decode supports arbitrary GQA ratio (was crash for G>32, scalar fallback for G>16)
__launch_bounds__on all MMA and prefill kernels for register allocation hints- 4x vectorized combine kernel (4 head_dim per thread, grid launch reduced 4x)
.L2::128Bcache hint on allcp.asyncPTX- uint4 vectorized K loads in scalar decode kernels
- Unified dispatcher header: compile-time kernel traits + causal/mask dispatch
- Fixed
alloc_split_partialsusing uninitializednum_splits→ always allocate withMAX_SPLITS=32 - Extracted
warp_reduce_sum,bf16,MAX_SPLITStoattn_warp_utils.cuh
Training
- FSDP2Executor using
torch.distributed.fsdp.fully_shard(no FlatParameter wrapper, zerouse_orig_paramshack) - Online rollout framework for RL strategies (RLOO/GRPO)
- SIGTERM/SIGINT auto-checkpoint with DDP support
BaseExecutor.preparerefactored: model/optimizer/scheduler via factoriestrain_context.pyrewritten for checkpoint-before-wrap ordering- Default
max_grad_norm=1.0
Inference
- Attention dimension dispatch:
MAX_DIM=256fast path vs generic path - Eliminated GPU syncs in contiguous cache write/gather hot paths
- KV-cache path unified for rollout and inference engine
- Attn_mask and loss_mask separated in
get_logprobs - Causal masking composed in strategy
Preprocessing & Data
- Batch tokenizer encoding and
apply_chat_template - Direct SFT from JSONL without
dataset_config.json - LoRA created on base weight device instead of CPU
- Config field names aligned with HuggingFace convention
Misc
- Simplified attention mask handling (mask=None for full causal)
- LoRA injection before checkpoint
state_dictloading - Binary encode/decode utilities for dataset storage binding
- Dedup conversion in sampling API
- Comprehensive tests: 355+382 lines for online strategy and rollout
Test Coverage
- All 22 CUDA kernel tests pass
- All 202+ Python inference tests pass
- New: signal handler tests, online RL e2e/strategy/rollout tests
v1.3.10
Storage / Dataset (major refactor)
- Store composition:
Storebase +Streamable/Recordablemixins replace diamond inheritance. RemovedRecordDataset,get_index, and all window/stride logic from Dataset layer - Store owns indexing:
__getitem__/__len__/sample_window/token_count/num_sampleslive on Store. Dataset is a pure delegator binding Store to train-type key mapping - DatasetFactory._store_window_for**: record datasets (DPO/GRPO) force
window_size=0to prevent stream semantics - JsonlStore lazy mode:
processor=fnkeeps raw JSON records, defers tokenization tofetch_record— DPO/GRPO trains directly from.jsonlwithout pre-tokenization - TokenizeTransform: bridges raw JSON→tensors with shared preprocessing core (tokenizer + mask-builder + position-ids)
- Preprocessing core.py: ~60% of Pipeline logic shared with TokenizeTransform via
build_preprocessing_components,iter_raw_records,primary_ids,to_per_record_tensors - MmapStore: multi-shard support with per-record
_offsets; docstring conforms to read-only memmap (mode="r") segments_are_recordsclass attribute differentiates H5/JSONL (per-record) from bin (opaque shards)
Training
- MuonMix optimizer: Muon for 2D weight matrices, AdamW for 1D (bias/norm/embed/head). Inherits from
torch.optim.Optimizerfor proper scheduler interop.param_groupsmerged from both sub-optimizers - DPO:
reduction="sum"(wasmean); ref_model injected externally instead of created frommodel_fn; applies chat template during tokenization - GRPO: separates old policy (behaviour, synced externally) from ref model (frozen SFT checkpoint, KL term only). Token-level logprobs with prompt masking. Group-normalized advantages with unbiased std. No more
sync_interval --resumeflag: decouples weight loading from checkpoint restoration (epoch, consumed_samples, optimizer & scheduler state).Trainer.train(param_path=, resume=)- Optional
max_grad_norm:Nonedisables clipping, logs raw grad norm instead - Distributed checkpoint:
Executor.checkpoint_context()for coordinated multi-GPU save/load withrank0_onlyfull state dict
Preprocessing
- MultiOutputMaskBuilder:
process_list_fieldreturns per-element boundaries (list of lists) critical for GRPO[G, R]tensor construction. Adds"value"action section type for scalar rewards - bfd_split packing:
plan_bfdexported as pure function; Best-Fit Decreasing on truncated sequence lengths with index-based bin plan so callbacks can apply same plan to aligned keys - Raw
.jsonfile support (not just JSONL) in Pipeline StageBuilder: factored from Pipeline for reusable preprocessing stages
Inference
- Frequency penalty: linear per-occurrence penalty scaled by
penalty × count(token).rep_windowlimits history to sliding window. Wired throughTask,Executor,sample()pipeline write_positions: per-row positional write forContiguousCacheView— fixes mixed-position decode in continuous batching (each task writes K/V at its own position)- StreamDecoder: buffers incomplete multi-byte tokens, emits text only after character is complete. Eliminates U+FFFD replacement characters in streaming output.
decode_new_token()/flush_remaining()onTask - Merged decode batch: removed per-position group batching (
pos_groups). All decode tasks run in a singleexecute_decodecall — simpler, higher throughput - Greedy decode:
temperature=0short-circuits tologits.argmax(dim=-1)inSamplingPipeline.sample()and module-levelsample().GenerationRequestvalidatestemperature >= 0 - Simplified scheduler loop: StreamDecoder-based callbacks, removed per-iteration tokenizer decode call
InferenceEngine.generate()exposesfrequency_penaltyandrep_windowparameters
CUDA kernels (csrc/)
- HEAD_DIM=32 support added to all attention kernels
- Paged decode CUDA kernel wired to Python extension via
ops.py - Double-buffered KV pipeline + Q direct-to-register in decode MMA kernel (~1.27× on L20)
cp.asyncK/V loads + XOR swizzle + pre-scaled Q in both prefill and decode MMA kernels- Fused decode combine kernel: single-pass online-rescale reduction (halves
expfcalls) - Split-K (FlashDecoding) for decode MMA — fills idle SMs, 2.1–2.5× vs torch SDPA on low-parallelism workloads
- Enlarged prefill KV tile to BC=32 for D≤128 (~6-8% faster)
- Post-multiply attention scale in float (reduces causal max error 2⁻⁶ → 2⁻⁸)
- Fast-math + vectorization nvcc/host build flags
- Increased decode split-K parallelism for short sequences
- Unified
gqa_*→attn_*naming with_split_q/_split_kv/_mmastrategy suffixes - Template
AttentionParams, extracted shared MMA utils - Split extension into
loader.py(.sodiscovery) +ops.py(wrapper + fallback with layout/mask/scale helpers) - Removed ineffective
__launch_bounds__from prefill kernel
Fixes
np.memmapopenedmode="r"— prevents accidental data corruption from writes to disk-backed memory- Tool parser:
_parse_tool_call_jsonusesjson.loadsinstead of greedy regex with broken brace-stripping. Correctly handles nested object arguments, field-order-independent (no longer requires{"name":as first field) - Tokenizer
__getattr__: guard for private attrs prevents infinite recursion during unpickle (spawn multiprocessing fix) - Resume: optimizer LR curve restores correctly; step display and
consumed_samplesalignment across checkpoint boundaries - DPO: chat template applied in tokenization; sequence logprob uses sum (not mean) reduction
- GRPO: token-level ratio instead of sequence-level; prompt masking for correct response-only loss; unbiased std for group advantage normalization
- Auto-assign free port in
spawn_parallel_fnto avoidEADDRINUSE - System prompt handling made optional across scripts
- Prefill mask index order corrected (
batch×q_len×kv_len→batch×kv_len) - Support single
.h5file inload_h5 - tqdm postfix set before first update so step 1 shows live metrics
- MMLU: option permutation to handle answer position bias
- IFEval: switched from raw URL download to HuggingFace
datasetslibrary
Tests
tests/data/test_dataset.py: +696 lines — JSONL lazy/eager, MmapStore edge cases, dual-mode H5Store, DPO/GRPO tokenization, Store composition teststests/inference/test_sample.py: +106 lines — frequency penalty scalar/tensor/batch/masked, temperature strategytests/trainer/test_grpo_strategy.py: +224 lines — shapes, reduction modes, 3D batch, no-reduction-param pathtests/data/test_preprocess_pipeline.py: +67 lines — pipeline end-to-end, edge casestests/data/test_preprocess_builder.py: MultiOutputMaskBuilder parity teststests/data/test_sampler.py: RDSampler tests- Standalone CUDA tests:
attn_prefill_test.cu,attn_decode_test.cu,attn_paged_decode_test.cu - Benchmark for production MMA attention paths (FLOP/s + bandwidth)
Docs
- Full sync of
architecture.md,inference.md,dataflow.md,training.md,params.md,preprocessing.mdto actual code - README / README-zh-CN install instructions updated
- HuggingFace org from
ViperEktoViperEkura
v1.3.9
Features
- CUDA kernel system (
csrc/) — optional build, auto-detects sm_80+ for MMA tensor-core paths. Adds fused GQA decode attention, tensor-core prefill/decode MMA kernels, paged decode attention (scalar + MMA), split-KV (FlashDecoding). Fallback totorch SDPAwhen.somissing - MuonMix optimizer — Muon for 2D weight matrices, AdamW for 1D params (bias, norm, embedding, LM head). Replaces plain AdamW
- DPO / GRPO data pipeline —
MultiOutputMaskBuildersplits preprocessing into single-output (SFT/pretrain) and multi-output (DPO/GRPO), with"value"action section type for scalar rewards - HEAD_DIM=32 support added to all attention kernels
- Paged decode CUDA kernel wired to Python extension via
ops.py
Performance
- Double-buffered KV pipeline + Q direct-to-register in decode MMA kernel (~1.27× on L20)
cp.asyncK/V loads + XOR swizzle + pre-scaled Q in both prefill and decode MMA kernels- Fused decode combine kernel: single-pass online-rescale reduction (halves
expfcalls) - Split-K (FlashDecoding) for decode MMA — fills idle SMs, 2.1–2.5× vs torch SDPA on low-parallelism workloads
- Enlarged prefill KV tile to BC=32 for D≤128 (~6-8% faster)
- Post-multiply attention scale in float (reduces causal max error 2^-6 → 2^-8)
- Fast-math + vectorization nvcc/host build flags
- Increased decode split-K parallelism for short sequences
Refactors
- Unified
gqa_*→attn_*naming with_split_q/_split_kv/_mmastrategy suffixes - Template
AttentionParams, extracted shared MMA utils - Split extension into
loader.py(.sodiscovery) +ops.py(wrapper + fallback) - Removed ineffective
__launch_bounds__from prefill kernel
Fixes
- Auto-assign free port in
spawn_parallel_fnto avoidEADDRINUSE - Restore resident Qa register to fix sQ overwrite bug in prefill MMA
- Exclude embedding/LM head/bias/norm from Muon optimizer
MuonMixinherits fromtorch.optim.Optimizer- Correct prefill mask index (batch×q_len×kv_len → batch×kv_len)
- Support single
.h5file inload_h5 - tqdm postfix set before first update so step 1 shows metrics
Docs
- Full sync of 6 doc files to actual code
- Fix errors across README,
architecture.md,inference.md,dataflow.md,training.md,params.md,preprocessing.md - Update install instructions (EN/CN)
Tests
- Standalone CUDA tests:
attn_prefill_test.cu,attn_decode_test.cu,attn_paged_decode_test.cu - Benchmark for production MMA attention paths (FLOP/s + bandwidth)
- Parity tests for single/multi output mask builders
v1.3.8
Changelog
v1.3.8 (2026-07-05)
Features
- LoRA fine-tuning module with low-rank adapter injection and persistence
- Tool-call parsing layer with vLLM-style BaseToolParser/SimpleJsonToolParser
- ROUGE, IFEval, IFD, HumanEval evaluation scripts
- WSD learning rate scheduler
- BFD bin-packing strategy for data preprocessing
- JSONL dataset store (JsonlStore) with on-the-fly tokenization
- Preprocessing pipeline with position_ids precompute and DPO/GRPO multi-output
- val_split/val_step/metrics/log CLI args for training
- NEFTune noise injection in Embedding
- SVD weight analysis script
- scheduler min_rate default unification
- Gradient checkpointing support in training script
- load_json/load_safetensors broadcast mechanism for cross-node distributed loading
Refactors
- Unified serialization layer into astrai.serialization package, moved dataset I/O out of storage.py
- Inference API: tool parser dependency injection, lazy FastAPI singleton, GenContext.created fix
- MetricCallback: merged validation, event-typed logging, optimizer-step granularity
- Trainer: replaced iteration tracking with consumed_samples, grad_norm moved to executor
- Pipeline: strategy-based packing/position-id/writer, eliminated _flush if/else branches
- Executor: unwrap_model returns state_dict directly, clip_grad_norm unified, use_orig_params hardcoded
- Launch strategy refactored with TorchrunStrategy/LocalStrategy, local_rank decoupled
- DecoderBlock: accepts config object instead of 16 individual params
- BaseFactory: generic type auto-resolution, dead code cleanup
- Compacted test code, removed Muon optimizer, upgraded torch 2.11.0+cu128
Fixes
- SFT pipeline position_ids default & doc boundary preservation
- bool attention mask with packed SFT doc boundary masking
- Preprocessing pipeline: 4 critical issues resolved
- Scheduler: division-by-zero, loss_mask bool casting
- Sampler: reset iter at epoch end for correct progress bar
- Checkpoint: consumed_samples restores sampler position; unwrap DDP/FSDP avoids module. prefix
- Storage: multi-shard meta.json recursive discovery
- ForwardRef._evaluate Python 3.12 compatibility
- MMLU: chat template formatting matched to SFT training
- Created timestamp, bin multi-shard overwrite
- generate.py: standardized CLI interface
- Early abort on task_extend failure; improved scheduler crash cleanup
Docs
- architecture.md: removed TrainConfig.log_interval from class diagram, split KVCache into abstract + PageCache/ContiguousCache, split KvcacheView into CacheView + PageCacheView/ContiguousCacheView, added JsonlStore, fixed GradientCheckpointingCallback type and CheckpointCallback typo
- training.md: added position_ids to SFT strategy keys, fixed callback hook table to match actual hooks, removed merged ValidationCallback
- inference.md: replaced single KVCache facade with ContiguousCache (default) and PageCache (paged) documentation
- dataflow.md: added JsonlStore to storage backends and format detection
- params.md: removed nonexistent --log_interval parameter
- preprocessing.md: updated timestamp
Tests
- Completed inference protocol layer unit test coverage
- Added LoRA module tests
- Filled storage layer test gaps
- Added SFT test data with position_ids field
- Added tool parser tests
v1.3.7
Features
- FSDP parallel backend with zero-redundancy sharded training
- LoRA fine-tuning module with low-rank adapter injection and persistence
- NTK-Aware RoPE dynamic scaling, extending context window limit
- MMLU evaluation script for standardized model knowledge assessment
- load_json/load_safetensors broadcast mechanism for cross-node distributed loading
Refactors
- Storage layer refactored to Store pattern, removed Fetcher layer, supporting multi-segment data with explicit length
- Training backend refactored to Executor pattern (none/ddp/fsdp), decoupling parallel logic
- Inference protocol layer refactored to Strategy/Builder pattern with independent OpenAI/Anthropic responders
- Unified serialization layer, eliminating scattered I/O paths
- Removed JSONStore from data pipeline, unified to H5/Bin dual format
- Simplified _disable_random_init, moved scheduler into sync block
- Removed -> None return annotations, split FSDP parameters
Fixes
- Disabled DDP static_graph to prevent no_sync/backward conflict under PyTorch 2.7.1
- Checkpoint resume restores optimizer/scheduler state and sampler remaining length
- Unwrap DDP/FSDP on checkpoint save to avoid module. prefix
- start_epoch/start_batch determined by user args, no longer overridden by checkpoint
- Left padding in perplexity.py causing incorrect PPL with batch>1
- Storage multi-segment bug, switched JSON to JSONL
- Early abort on task_extend failure after decode, notify waiting tasks on scheduler crash
Docs
- Synced architecture/training/inference/dataflow/params docs to actual code
Tests
- Completed inference protocol layer unit test coverage
- Added LoRA module tests
- Filled storage layer test gaps
v1.3.6
v1.3.6 Release Notes
Refactor
- Renamed Transformer to AutoRegressiveLM, added EmbeddingEncoder
- Restructured training loop to two-level iteration (epoch → batch × grad_accum_steps), unified parameter naming
- Unified Config serialization via BaseConfig base class; to_dict() now supports list types
- Storage switched to factory pattern (StorageFactory), server reload via uvicorn
- Factory kwargs filtering and component parameter cleanup
- Checkpoint saves per HF convention (.pt extras), callback-managed restore
- Renamed module.py to components sub-package (attention, mlp, norm, embedding, etc.)
- Replaced uniform normal_(0.006) with recursive sub-module _init_weights
- generate_ar switched to streaming output
- TrainConfig added metric fields (log_dir, log_interval, metrics); metric_logger uses **kwargs passing
- ProgressBarCallback added log_interval/file params, default output to sys.stdout
- Timestamps unified to ISO 8601 format across checkpoint and metric logger
Features
- BaseModelConfig + DeepSeekMoE + factory pattern replacing if/else branching
- GradientCheckpointingCallback for activation checkpointing (torch.compile compatible)
- Muon optimizer
- Validation loop in training
- Dataset field validation on load
Bug Fixes
- Fixed MLA bugs: kv_b_proj output dim, q_rope split offset, config passthrough, rope_theta ignored, tie_weight None silently taking effect
- Fixed training loop parameter passing and train script argument issues
- Fixed AdamW hyperparameter defaults and doc examples
- Fixed total_steps using ceiling to match actual step count
- Fixed LR scheduler step counting by optimizer step, prevented warmup overflow
- Fixed mp.start_processes daemon=False causing subprocess creation failure
- Removed redundant request parameter, improved tokenizer robustness
- Fixed Docker Compose UID/GID defaults and docker.sh logs command
- Fixed to_dict() silently dropping list-type fields (metrics, gradient_checkpointing_modules)
- Fixed OpenAI API stop parameter being completely ignored
Tests
- Added 6 architecture configuration × 2 scenario forward pass tests
- Added stop parameter non-stream/stream tests for OpenAI endpoint
Docs
- Split documentation and added missing classes and relationship lines in class diagrams
- Fixed class names, method signatures, and module references across doc files
- Updated architecture.md: TrainConfig/CheckpointCallback/ProgressBarCallback/MetricLoggerCallback fields, relationship classification, ChatCompletionRequest Optional types
- Updated bilibili video link
- Removed stale ModelConfig export from config/init.py
v1.3.5
v1.3.5 Release Notes
Refactor
- Rewrote training loop: fixed step/backward ordering, restructured as triple-nested loop (epoch → accumulation window → batch)
- Extracted
BaseStorageabstraction for JSON raw text data loading PagedCacheFacade pattern: extractedPagePool/PrefixCache/TaskTable- Decoupled
Executor/Scheduler/TaskManager, removedServerStateglobal singleton - Unified
RotaryEmbeddingcos/sin into a single complex buffer (freqs_cis) - Eliminated redundant patterns across the codebase, unified factory and parameter passing
Features
- GRPO CLI integration with on-policy training
- OpenAI/Anthropic-compatible APIs, Docker Compose one-click deployment (GPU/CPU dual mode)
- Prefix cache with LRU eviction for inference engine
_generate_streamingnow supports batch mode- Checkpoint
extrafield for user-defined extensible save/load top_kparameter exposed to OpenAI-compatible API
Bug Fixes
- Fixed incorrect step/backward order in training loop
- Fixed in-place write alias error in
process_attention_maskafter expand - Fixed
MultiSegmentFetchercrash on empty dict; replacedBaseDatasetasserts with explicit raises - Fixed page cache allocation OOB crash and length overflow termination
- Fixed prefill attention mask length mismatch causing expand crash
- Fixed
max_seq_lencheck: only send STOP on prompt overflow; clamp max_tokens instead - Fixed multiple correctness and concurrency issues in batch decode
- Added chat template and system prompt to batch inference example
Performance
- DDP: enabled
gradient_as_bucket_view/static_graph/broadcast_buffers, AdamW fused - Replaced
waiting_queuelist withdeque;pull_candidatesfrom O(n²) to O(1) apply_rotary_embswitched to complex multiplication- Eliminated GPU sync in
RotaryEmbedding.forwardposition_ids lookup - Eliminated GPU sync in
PagedCache.writeposition_ids derivation (~15% decode speedup) - Vectorized
gatheroperation
Tests
- Added 13+ edge case tests
- Completed unit test coverage for inference module: cache, sample, engine, task
- Test optimizations: session-scoped model, Event-based scheduler sync
Docs
- Fixed class names, method signatures, and module references across 6 doc files
- Added training parameter tables
- Added model download steps to README