@mlx-node/trl 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,621 @@
1
+ /**
2
+ * GRPO Training Engine - Rust-Native Training
3
+ *
4
+ * This module provides a Rust-native GRPO training engine that minimizes
5
+ * FFI overhead by keeping the training loop entirely in Rust.
6
+ *
7
+ * ## Key Features
8
+ * - Training loop runs in Rust (eliminates FFI overhead)
9
+ * - Built-in reward functions (tool use, XML format, length, JSON schema)
10
+ * - Custom JS rewards via callback pattern
11
+ * - Gradient accumulation and memory management in Rust
12
+ * - High-level train() method for full training runs
13
+ * - Low-level trainStep() for custom training loops
14
+ *
15
+ * ## High-Level Usage (train with dataset)
16
+ * ```typescript
17
+ * const trainer = await GRPOTrainer.create({
18
+ * modelPath: './model',
19
+ * modelName: 'qwen3-0.6b',
20
+ * rewardFunction: (prompts, completions) => [...scores],
21
+ * });
22
+ * await trainer.train(dataset);
23
+ * ```
24
+ *
25
+ * ## Low-Level Usage (step-by-step)
26
+ * ```typescript
27
+ * const model = await Qwen3Model.load(modelPath);
28
+ * const trainer = new GRPOTrainer(model, config);
29
+ *
30
+ * trainer.registerBuiltinReward({
31
+ * rewardType: 'ToolUse',
32
+ * allowedTools: ['search', 'calculate'],
33
+ * });
34
+ *
35
+ * for (const batch of dataset) {
36
+ * const completions = await trainer.generateBatch(batch.prompts);
37
+ * const rewards = await myRewardFunction(batch.prompts, completions);
38
+ * const metrics = await trainer.trainStep(batch.prompts, rewards);
39
+ * }
40
+ * ```
41
+ */
42
+ import { GrpoTrainingEngine, NativeRewardRegistry, OutputStore, type EngineEpochMetrics, type BuiltinRewardConfig, type GenerateBatchResult as NativeGenerateBatchResult, type ToolDefinition } from '@mlx-node/core';
43
+ import { type TrainableModel } from '@mlx-node/lm';
44
+ import type { ChatMessage, DatasetExample, RewardFunction } from '../types.js';
45
+ import { type TrainingLogger } from './training-logger.js';
46
+ export { GrpoTrainingEngine, NativeRewardRegistry, OutputStore } from '@mlx-node/core';
47
+ export type { GrpoEngineConfig, EngineStepMetrics, EngineEpochMetrics, BuiltinRewardConfig, TrainStepResult, TrainStepResultWithOutputs, RewardOutput, OutputStoreConfig, } from '@mlx-node/core';
48
+ /**
49
+ * Configuration for GRPOTrainer
50
+ */
51
+ export interface GRPOTrainerConfig<T = unknown> {
52
+ modelPath?: string;
53
+ modelName?: string;
54
+ learningRate?: number;
55
+ gradientAccumulationSteps?: number;
56
+ gradientClipNorm?: number;
57
+ weightDecay?: number;
58
+ numEpochs?: number;
59
+ batchSize?: number;
60
+ groupSize?: number;
61
+ clipEpsilon?: number;
62
+ klCoef?: number;
63
+ lossType?: 'grpo' | 'dapo' | 'dr_grpo' | 'bnpo';
64
+ advantageNormalization?: boolean;
65
+ /** Maximum completion length for both generation and training (default: 256).
66
+ * Matches Python TRL's max_completion_length config. */
67
+ maxCompletionLength?: number;
68
+ temperature?: number;
69
+ topP?: number;
70
+ topK?: number;
71
+ repetitionPenalty?: number;
72
+ /**
73
+ * Tool definitions for function calling.
74
+ * When provided, tools are included in the chat template so the model
75
+ * can generate tool calls. Essential for tool-use training.
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * import { createToolDefinition } from '@mlx-node/lm';
80
+ *
81
+ * const config: GRPOTrainerConfig = {
82
+ * tools: [
83
+ * createToolDefinition('lsp', 'Query API docs', { method: { type: 'string' } }, ['method']),
84
+ * createToolDefinition('run_js', 'Execute code', { code: { type: 'string' } }, ['code']),
85
+ * ],
86
+ * };
87
+ * ```
88
+ */
89
+ tools?: ToolDefinition[];
90
+ /** Enable thinking mode for Qwen3 models (default: true).
91
+ * When false, adds empty <think></think> tags to disable model thinking.
92
+ * This is useful for tool-use training where you want direct outputs. */
93
+ enableThinking?: boolean;
94
+ rewardType?: 'function' | 'builtin' | 'model';
95
+ rewardFunction?: RewardFunction<T>;
96
+ rewardModelPath?: string;
97
+ gradientClipValue?: number;
98
+ logInterval?: number;
99
+ saveInterval?: number;
100
+ evalInterval?: number;
101
+ outputDir?: string;
102
+ logConsole?: boolean;
103
+ logJsonl?: boolean;
104
+ runName?: string;
105
+ /** Maximum number of checkpoints to keep (default: 3). Set to 0 for unlimited. */
106
+ maxCheckpoints?: number;
107
+ device?: string;
108
+ /** Resume training from a checkpoint directory, or 'latest' to auto-find */
109
+ resumeFromCheckpoint?: 'latest' | string;
110
+ /** Enable TUI mode - outputs structured JSONL to stdout and listens for commands on stdin */
111
+ tuiMode?: boolean;
112
+ /**
113
+ * Timeout for the reward function callback in milliseconds.
114
+ *
115
+ * If your reward function calls external APIs or performs expensive
116
+ * computations, you may need to increase this value.
117
+ *
118
+ * Set to 0 to disable timeout (not recommended for production).
119
+ *
120
+ * @default 60000 (60 seconds)
121
+ */
122
+ rewardTimeout?: number;
123
+ /**
124
+ * Batch chunk size for LM head computation (memory optimization).
125
+ * When set, the LM head (hidden_states -> logits) is computed in chunks
126
+ * of this size to reduce peak memory usage.
127
+ * Default: undefined (no chunking, full batch at once)
128
+ * Recommended: 2 for batch_size >= 4 with large vocabularies (e.g., Qwen3 with 151936 vocab)
129
+ * This reduces peak memory from ~1.2GB to ~300MB for Qwen3.
130
+ */
131
+ lmHeadChunkSize?: number;
132
+ /**
133
+ * Batch chunk size for transformer forward pass (memory optimization).
134
+ * When set, the transformer layers process the batch in chunks of this size,
135
+ * reducing peak memory from O(batch × heads × seq²) for attention.
136
+ * Default: undefined (no chunking, full batch at once)
137
+ * Recommended: 4 for batch_size >= 4 with groupSize >= 4
138
+ * Memory savings: ~70-80% for batch=4, groupSize=4 (16 sequences → 4 at a time)
139
+ */
140
+ forwardChunkSize?: number;
141
+ /**
142
+ * Enable true parallel batch generation (default: false).
143
+ * When true, all N*G sequences are processed in parallel using batched FFI
144
+ * with per-sequence RoPE offsets. This provides 2-4x speedup for GRPO training.
145
+ * When false, uses sequential generation (process one prompt at a time,
146
+ * then expand KV cache for G completions).
147
+ */
148
+ useParallelBatchGeneration?: boolean;
149
+ /**
150
+ * Enable gradient checkpointing (default: true).
151
+ * Discards intermediate activations during forward pass and recomputes during backward,
152
+ * reducing peak memory from O(num_layers) to O(1) for intermediate states.
153
+ * For Qwen3.5 0.8B, this reduces autograd peak from ~105GB to ~11GB.
154
+ * Trade-off: ~30% more compute (one extra forward pass per layer during backward).
155
+ */
156
+ gradientCheckpointing?: boolean;
157
+ /** Optimizer type: 'sgd' or 'adamw' (default: 'adamw') */
158
+ optimizerType?: 'sgd' | 'adamw';
159
+ /** AdamW beta1 (default: 0.9) */
160
+ adamwBeta1?: number;
161
+ /** AdamW beta2 (default: 0.999) */
162
+ adamwBeta2?: number;
163
+ /** AdamW epsilon (default: 1e-8) */
164
+ adamwEps?: number;
165
+ /**
166
+ * Chunk size for vocabulary dimension in cross-entropy computation.
167
+ * When computing logsumexp over large vocabularies (e.g., Qwen3's 151,936 tokens),
168
+ * the computation is split into chunks of this size to reduce peak memory usage.
169
+ *
170
+ * Default: 65536 (2^16)
171
+ *
172
+ * Memory impact for Qwen3 (vocab=151936):
173
+ * - Standard: Full [B, T, 151936] intermediate tensor
174
+ * - Chunked (65536): 3 chunks, ~2.3x lower peak memory
175
+ *
176
+ * Set to a larger value (e.g., 262144) to reduce chunking overhead,
177
+ * or smaller value (e.g., 32768) for tighter memory constraints.
178
+ */
179
+ vocabChunkSize?: number;
180
+ /** Output recording configuration (records all generations for debugging/research) */
181
+ outputStore?: {
182
+ /** Enable output recording (default: false) */
183
+ enabled: boolean;
184
+ /** Local database path (default: "{outputDir}/outputs.db") */
185
+ localPath?: string;
186
+ /** Remote Turso URL for cloud sync (optional) */
187
+ remoteUrl?: string;
188
+ /** Turso auth token (required if remoteUrl is set) */
189
+ authToken?: string;
190
+ /** Sync interval in seconds (default: 60, only for embedded replica mode) */
191
+ syncInterval?: number;
192
+ };
193
+ }
194
+ /**
195
+ * Dataset metadata for resume validation
196
+ *
197
+ * Stored in checkpoints to validate that the same dataset is used on resume.
198
+ * Prevents issues where batch indices don't align due to dataset changes.
199
+ */
200
+ export interface DatasetMetadata {
201
+ /** Total number of examples in the dataset */
202
+ size: number;
203
+ /** Hash of first N example prompts for identity check */
204
+ contentHash: string;
205
+ /** Shuffle seed if deterministic shuffling was used */
206
+ shuffleSeed?: number;
207
+ /** Indices of batches already processed in current epoch */
208
+ processedBatchIndices?: number[];
209
+ }
210
+ /**
211
+ * Training state saved with checkpoints for resumption
212
+ */
213
+ export interface TrainingState {
214
+ step: number;
215
+ epoch: number;
216
+ timestamp: string;
217
+ /** Dataset information for resume validation */
218
+ dataset?: DatasetMetadata;
219
+ /** Whether optimizer state was saved alongside this checkpoint */
220
+ hasOptimizerState?: boolean;
221
+ }
222
+ /**
223
+ * Result from generateBatch with detailed information
224
+ */
225
+ export interface GenerateBatchResult {
226
+ /** Generated completion texts */
227
+ completionTexts: string[];
228
+ /** Native generation result for passing to trainStepWithGenerations */
229
+ nativeResult: NativeGenerateBatchResult;
230
+ /** Completion token counts (derived from nativeResult) */
231
+ tokenCounts: number[];
232
+ /** Finish reasons for each completion ("stop", "length", or "repetition") */
233
+ finishReasons: string[];
234
+ }
235
+ /**
236
+ * Default configuration
237
+ */
238
+ export declare const DEFAULT_GRPO_CONFIG: GRPOTrainerConfig;
239
+ /**
240
+ * Training step metrics (compatible with both old and new APIs)
241
+ */
242
+ export interface TrainStepMetrics {
243
+ /** Current step number */
244
+ step: number;
245
+ /** GRPO loss value */
246
+ loss: number;
247
+ /** Mean reward across completions */
248
+ meanReward: number;
249
+ /** Standard deviation of rewards */
250
+ stdReward: number;
251
+ /** Mean advantage value */
252
+ meanAdvantage: number;
253
+ /** Std of advantages - indicates reward variance within groups */
254
+ stdAdvantage: number;
255
+ /** Total tokens generated this step */
256
+ totalTokens: number;
257
+ /** Whether gradients were applied */
258
+ gradientsApplied?: boolean;
259
+ /** Time for generation (ms) */
260
+ generationTimeMs?: number;
261
+ /** Time for training (ms) */
262
+ trainingTimeMs?: number;
263
+ /** Current epoch (for high-level API) */
264
+ epoch?: number;
265
+ }
266
+ /**
267
+ * Legacy type alias for backward compatibility
268
+ */
269
+ export type TrainingMetrics = TrainStepMetrics;
270
+ /**
271
+ * Compute a hash of dataset content for identity checking on resume.
272
+ *
273
+ * Hashes the first N examples to create a fingerprint that can detect
274
+ * if the dataset has been modified between training runs.
275
+ *
276
+ * @param dataset - Array of dataset examples
277
+ * @param sampleSize - Number of examples to hash (default: 10)
278
+ * @returns 16-character hex hash string
279
+ */
280
+ export declare function computeDatasetHash(dataset: DatasetExample[], sampleSize?: number): string;
281
+ /**
282
+ * Error thrown when a reward function times out.
283
+ */
284
+ export declare class RewardTimeoutError extends Error {
285
+ readonly timeoutMs: number;
286
+ constructor(message: string, timeoutMs: number);
287
+ }
288
+ /**
289
+ * GRPO Trainer - Rust-Native Training Engine
290
+ *
291
+ * Provides a TypeScript-friendly interface to the Rust training engine.
292
+ * Supports both high-level training (train()) and low-level step-by-step (trainStep()).
293
+ */
294
+ export declare class GRPOTrainer<T = unknown> {
295
+ private engine;
296
+ private model;
297
+ private config;
298
+ private rewardFn?;
299
+ private currentEpoch;
300
+ private currentStep;
301
+ /** Original model path (for tokenizer files when saving checkpoints) */
302
+ private originalModelPath?;
303
+ private paused;
304
+ private stopRequested;
305
+ private stdinInterface?;
306
+ private logger;
307
+ private sampleDisplayMode;
308
+ private outputStore?;
309
+ private outputStoreInitPromise?;
310
+ private outputStoreRunId?;
311
+ private outputStorePath?;
312
+ private lastCheckpointStep;
313
+ private signalHandlersInstalled;
314
+ private lastGoodCheckpointPath;
315
+ private lastGoodCheckpointStep;
316
+ private datasetMetadata?;
317
+ private processedBatchIndices;
318
+ /**
319
+ * Create a new GRPO trainer from a model
320
+ *
321
+ * @param model - Pre-loaded Qwen3 model
322
+ * @param config - Training configuration
323
+ */
324
+ constructor(model: TrainableModel, config?: Partial<GRPOTrainerConfig<T>>, logger?: TrainingLogger);
325
+ /**
326
+ * Setup stdin handler for TUI control commands
327
+ */
328
+ private setupStdinHandler;
329
+ /**
330
+ * Setup OS signal handlers for graceful shutdown on crash/interrupt
331
+ *
332
+ * Catches SIGTERM, SIGINT, and uncaught exceptions to:
333
+ * - Save emergency checkpoint (if > 10 steps since last)
334
+ * - Finalize OutputStore with 'crashed' status
335
+ * - Exit cleanly
336
+ */
337
+ private setupSignalHandlers;
338
+ /**
339
+ * Initialize the output store for recording training outputs
340
+ */
341
+ private initOutputStore;
342
+ /**
343
+ * Send minimal resume state to TUI for UI display only (no historical data)
344
+ *
345
+ * Used when resuming from checkpoint without a matching database run.
346
+ * Ensures TUI shows correct epoch/batch progress.
347
+ */
348
+ private sendResumeStateUiOnly;
349
+ /**
350
+ * Send resume state to TUI for restoring sparklines and aggregates
351
+ *
352
+ * Queries the database for historical metrics and aggregates, then sends
353
+ * to TUI via the resumeState message.
354
+ *
355
+ * @param runId - Database run ID
356
+ * @param actualStepsPerEpoch - Actual steps per epoch from dataset (if known)
357
+ */
358
+ private sendResumeState;
359
+ /**
360
+ * Ensure output store is initialized (lazy initialization for low-level API users)
361
+ * Uses promise mutex to prevent race conditions from concurrent calls.
362
+ *
363
+ * Call this method from custom training loops before starting training
364
+ * to enable database recording and TUI database tab.
365
+ */
366
+ ensureOutputStoreInitialized(): Promise<void>;
367
+ /**
368
+ * Get the output store (for querying recorded data)
369
+ */
370
+ getOutputStore(): OutputStore | undefined;
371
+ /**
372
+ * Handle a command received from stdin
373
+ */
374
+ private handleStdinCommand;
375
+ /**
376
+ * Wait for resume if paused, with polling
377
+ */
378
+ private waitForResume;
379
+ /**
380
+ * Create a trainer by loading a model from disk
381
+ *
382
+ * This is the recommended way to create a trainer for training runs.
383
+ * If resumeFromCheckpoint is set, loads from checkpoint instead of modelPath.
384
+ *
385
+ * @param config - Configuration including modelPath
386
+ * @returns Promise<GRPOTrainer>
387
+ */
388
+ static create<U>(config: GRPOTrainerConfig<U>): Promise<GRPOTrainer<U>>;
389
+ /**
390
+ * Find the latest checkpoint in the output directory
391
+ */
392
+ static findLatestCheckpoint(outputDir?: string): string | null;
393
+ /**
394
+ * Register a built-in reward function
395
+ *
396
+ * Built-in rewards run entirely in Rust with no FFI overhead.
397
+ *
398
+ * @example
399
+ * ```typescript
400
+ * // Tool use validation
401
+ * trainer.registerBuiltinReward({
402
+ * rewardType: 'ToolUse',
403
+ * allowedTools: ['search', 'calculate'],
404
+ * required: true,
405
+ * weight: 1.0,
406
+ * });
407
+ *
408
+ * // XML format validation
409
+ * trainer.registerBuiltinReward({
410
+ * rewardType: 'XmlFormat',
411
+ * requiredTags: ['thinking', 'answer'],
412
+ * weight: 0.5,
413
+ * });
414
+ *
415
+ * // Length-based reward
416
+ * trainer.registerBuiltinReward({
417
+ * rewardType: 'Length',
418
+ * minLength: 100,
419
+ * maxLength: 500,
420
+ * useChars: true,
421
+ * });
422
+ * ```
423
+ */
424
+ registerBuiltinReward(config: BuiltinRewardConfig): void;
425
+ /**
426
+ * Set a custom JavaScript reward function
427
+ *
428
+ * The function will be called after generation to compute rewards.
429
+ *
430
+ * @param fn - Reward function that takes prompts and completions
431
+ */
432
+ setRewardFunction(fn: RewardFunction<T>): void;
433
+ /**
434
+ * Generate completions for prompts
435
+ *
436
+ * Generates `groupSize` completions per prompt.
437
+ * Returns all data needed for training, including tokens and log probabilities.
438
+ *
439
+ * @param prompts - Array of chat conversations
440
+ * @returns GenerateBatchResult with completion texts and native generation data
441
+ */
442
+ generateBatch(prompts: ChatMessage[][]): Promise<GenerateBatchResult>;
443
+ /**
444
+ * Score completions using built-in rewards
445
+ *
446
+ * @param prompts - Prompt texts (one per completion)
447
+ * @param completions - Completion texts
448
+ * @returns Array of reward scores
449
+ */
450
+ scoreCompletions(prompts: string[], completions: string[]): number[];
451
+ /**
452
+ * Score generations using the configured reward function.
453
+ *
454
+ * Builds RewardOutput array with structured completion data and passes to reward function.
455
+ *
456
+ * @param prompts - Array of chat conversations
457
+ * @param completions - Generated completion texts
458
+ * @param context - Context for the reward function
459
+ * @param groupSize - Number of completions per prompt (optional, defaults to config.groupSize)
460
+ * @param tokenCounts - Token counts for each completion (optional, defaults to 0s)
461
+ * @param finishReasons - Finish reasons from generation (optional, e.g. "stop", "length", "repetition")
462
+ * @returns Promise<Float32Array> of reward scores
463
+ */
464
+ scoreGenerations(prompts: ChatMessage[][], completions: string[], context: T, groupSize?: number, tokenCounts?: number[], finishReasons?: string[]): Promise<Float32Array>;
465
+ /**
466
+ * Run a training step
467
+ *
468
+ * This method:
469
+ * 1. Generates completions with tokens and log probabilities
470
+ * 2. Computes rewards using the configured reward function
471
+ * 3. Trains using the SAME completions that were scored (no double-generation)
472
+ *
473
+ * @param prompts - Array of chat conversations
474
+ * @returns Training step metrics
475
+ */
476
+ trainStep(prompts: ChatMessage[][], context?: T): Promise<TrainStepMetrics>;
477
+ /**
478
+ * Run a complete training step with automatic reward computation
479
+ *
480
+ * This method combines generation, reward scoring, and training into a single
481
+ * Rust call, eliminating FFI overhead by keeping token data in Rust memory.
482
+ *
483
+ * 1. Generates completions with full token/logprob data (stays in Rust)
484
+ * 2. Calls JS reward function with RewardOutput[]
485
+ * 3. Performs training update using the in-memory data
486
+ *
487
+ * @param prompts - Array of chat conversations
488
+ * @param context - Context for the reward function
489
+ * @returns Training metrics and generated completions
490
+ */
491
+ trainStepAuto(prompts: ChatMessage[][], context?: T): Promise<{
492
+ metrics: TrainStepMetrics;
493
+ completions: string[];
494
+ rewards: number[];
495
+ completionLengths: number[];
496
+ }>;
497
+ /**
498
+ * Increment the step counter (for custom training loops)
499
+ *
500
+ * Call this after each training step when using low-level APIs like
501
+ * engine.trainStepWithGenerations() instead of trainer.trainStepAuto().
502
+ */
503
+ incrementStep(): void;
504
+ /**
505
+ * Get the current step number
506
+ */
507
+ getStep(): number;
508
+ /**
509
+ * Get the current epoch number
510
+ */
511
+ getEpoch(): number;
512
+ /**
513
+ * Record a training step to the output store database (for custom training loops)
514
+ *
515
+ * Use this when building custom training loops with engine.trainStepWithGenerations().
516
+ * The step number should be the value after incrementStep() was called.
517
+ *
518
+ * @param step - Step number
519
+ * @param metrics - Step metrics from the engine
520
+ * @param completions - Generated completion texts
521
+ * @param rewards - Reward values for each completion
522
+ * @param prompts - Prompt messages for each completion
523
+ */
524
+ recordStepToDatabase(step: number, metrics: {
525
+ loss: number;
526
+ meanReward: number;
527
+ stdReward: number;
528
+ meanAdvantage: number;
529
+ stdAdvantage: number;
530
+ totalTokens: number;
531
+ }, completions: string[], rewards: number[], prompts: string[]): Promise<void>;
532
+ /**
533
+ * Run a full training loop over a dataset
534
+ *
535
+ * This is the high-level training API that handles:
536
+ * - Epoch iteration
537
+ * - Batching
538
+ * - Generation and reward computation
539
+ * - Logging (if configured)
540
+ * - Checkpoint saving and resumption
541
+ * - TUI mode support (pause/resume, sample reporting)
542
+ *
543
+ * @param dataset - Array of DatasetExample items
544
+ */
545
+ train(dataset: DatasetExample[]): Promise<void>;
546
+ /**
547
+ * Save a checkpoint with model weights and training state
548
+ *
549
+ * Regular checkpoints (non-emergency) are tracked as "last known good" checkpoints.
550
+ * When NaN gradients occur, the emergency save logic can restore from the last good checkpoint.
551
+ *
552
+ * @param name - Checkpoint name (default: "checkpoint-{step}")
553
+ * @param options - Optional settings for checkpoint save behavior
554
+ * @param options.isEmergency - If true, this is an emergency checkpoint (debug state, not "good")
555
+ * @returns Path to saved checkpoint, or empty string if save was skipped due to corruption
556
+ */
557
+ saveCheckpoint(name?: string, options?: {
558
+ isEmergency?: boolean;
559
+ }): Promise<string>;
560
+ /**
561
+ * Remove old checkpoints, keeping only the most recent ones
562
+ * Preserves 'final' and 'emergency-*' checkpoints
563
+ */
564
+ private cleanupOldCheckpoints;
565
+ /**
566
+ * Start a new training epoch
567
+ */
568
+ startEpoch(): void;
569
+ /**
570
+ * End the current epoch and get metrics
571
+ *
572
+ * @param epochTimeSecs - Duration of the epoch in seconds
573
+ */
574
+ endEpoch(epochTimeSecs: number): EngineEpochMetrics;
575
+ /**
576
+ * Reset the trainer for a new training run
577
+ */
578
+ reset(): void;
579
+ /**
580
+ * Get current training step
581
+ */
582
+ get step(): number;
583
+ /**
584
+ * Get current epoch
585
+ */
586
+ get epoch(): number;
587
+ /**
588
+ * Get current micro-step within gradient accumulation
589
+ */
590
+ get microStep(): number;
591
+ /**
592
+ * Check if built-in rewards are configured
593
+ */
594
+ get hasBuiltinRewards(): boolean;
595
+ /**
596
+ * Get names of registered reward functions
597
+ */
598
+ get rewardNames(): string[];
599
+ /**
600
+ * Get the underlying native engine
601
+ *
602
+ * For advanced use cases that need direct access.
603
+ */
604
+ getNativeEngine(): GrpoTrainingEngine;
605
+ }
606
+ /**
607
+ * Create a standalone reward registry for testing rewards
608
+ *
609
+ * @example
610
+ * ```typescript
611
+ * const registry = createRewardRegistry();
612
+ * registry.register({
613
+ * rewardType: 'ToolUse',
614
+ * allowedTools: ['search'],
615
+ * });
616
+ *
617
+ * const score = registry.score('prompt', 'completion with <tool_call>...</tool_call>');
618
+ * ```
619
+ */
620
+ export declare function createRewardRegistry(): NativeRewardRegistry;
621
+ //# sourceMappingURL=grpo-trainer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grpo-trainer.d.ts","sourceRoot":"","sources":["../../src/trainers/grpo-trainer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAiBH,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,WAAW,EAGX,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,IAAI,yBAAyB,EAGrD,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAa,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9D,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAwB,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGjF,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAA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