@mlx-node/trl 0.0.13 → 0.0.15

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.
package/src/types.ts ADDED
@@ -0,0 +1,70 @@
1
+ // Re-export types from @mlx-node/core
2
+ export type { CompletionInfo, RewardOutput } from '@mlx-node/core';
3
+ import type { RewardOutput } from '@mlx-node/core';
4
+
5
+ // Re-export ChatRole from @mlx-node/lm (single source of truth)
6
+ export type { ChatRole } from '@mlx-node/lm';
7
+
8
+ export interface ChatMessage {
9
+ role: 'system' | 'user' | 'assistant' | 'tool' | (string & {});
10
+ content: string;
11
+ }
12
+
13
+ export interface CompletionMessage extends ChatMessage {}
14
+
15
+ export type Completion = CompletionMessage[];
16
+
17
+ export type DatasetSplit = 'train' | 'test' | (string & {});
18
+
19
+ export interface DatasetExample {
20
+ prompt: ChatMessage[];
21
+ metadata?: Record<string, unknown>;
22
+ }
23
+
24
+ export interface XmlParseResult {
25
+ reasoning: string | null;
26
+ answer: string | null;
27
+ isStrictMatch: boolean;
28
+ isSoftMatch: boolean;
29
+ errors: string[];
30
+ }
31
+
32
+ export interface RewardComputationInput {
33
+ prompts: ChatMessage[][];
34
+ completions: Completion[];
35
+ answers: (string | null)[];
36
+ }
37
+
38
+ /**
39
+ * Unified reward function type for GRPO training.
40
+ *
41
+ * Takes an array of RewardOutput objects containing structured completion data.
42
+ * Returns rewards for each completion (one per output).
43
+ */
44
+ export type RewardFunction<T = unknown> = (
45
+ outputs: RewardOutput[],
46
+ context: T,
47
+ ) => number[] | Float32Array | Promise<number[] | Float32Array>;
48
+
49
+ export interface PromptFormatterOptions {
50
+ includeOneShot?: boolean;
51
+ oneShotExample?: {
52
+ question: string;
53
+ reasoning: string;
54
+ answer: string;
55
+ };
56
+ }
57
+
58
+ export type PromptTemplate = (question: string, options?: PromptFormatterOptions) => ChatMessage[];
59
+
60
+ /**
61
+ * Converts a ChatMessage array to a string for reward function input
62
+ *
63
+ * This allows customization of how prompts are formatted as strings
64
+ * for different model architectures (Qwen3, Llama, etc.)
65
+ */
66
+ export type PromptFormatter = (messages: ChatMessage[]) => string;
67
+
68
+ export interface DatasetLoader {
69
+ load(split: DatasetSplit, limit?: number): Promise<DatasetExample[]>;
70
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Path security utilities to prevent directory traversal attacks.
3
+ *
4
+ * These utilities ensure that user-provided paths stay within allowed directories,
5
+ * preventing malicious paths like `../../../etc/` from accessing arbitrary files.
6
+ */
7
+
8
+ import { resolve as resolvePath, normalize, relative, isAbsolute } from 'node:path';
9
+
10
+ /**
11
+ * Error thrown when a path traversal attempt is detected.
12
+ */
13
+ export class PathTraversalError extends Error {
14
+ constructor(
15
+ public readonly resolvedPath: string,
16
+ public readonly allowedRoot: string,
17
+ ) {
18
+ super(`Path traversal detected: "${resolvedPath}" is outside allowed directory "${allowedRoot}"`);
19
+ this.name = 'PathTraversalError';
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Validates that a resolved path is contained within an allowed root directory.
25
+ * Prevents path traversal attacks via '../' sequences.
26
+ *
27
+ * @param resolvedPath - The fully resolved absolute path to validate
28
+ * @param allowedRoot - The root directory that paths must be contained within
29
+ * @throws PathTraversalError if path escapes the allowed root
30
+ */
31
+ export function validatePathContainment(resolvedPath: string, allowedRoot: string): void {
32
+ const normalizedPath = normalize(resolvedPath);
33
+ const normalizedRoot = normalize(allowedRoot);
34
+
35
+ // Get relative path from root to target
36
+ const relativePath = relative(normalizedRoot, normalizedPath);
37
+
38
+ // If relative path starts with '..' or is absolute, it's outside the root
39
+ if (relativePath.startsWith('..') || isAbsolute(relativePath)) {
40
+ throw new PathTraversalError(resolvedPath, allowedRoot);
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Resolves a user-provided path and validates it stays within an allowed root.
46
+ *
47
+ * @param userPath - The user-provided path (may be relative or absolute)
48
+ * @param allowedRoot - The root directory that the path must be contained within
49
+ * @returns The resolved absolute path
50
+ * @throws PathTraversalError if the resolved path escapes the allowed root
51
+ */
52
+ export function resolveAndValidatePath(userPath: string, allowedRoot: string): string {
53
+ const resolved = resolvePath(allowedRoot, userPath);
54
+ validatePathContainment(resolved, allowedRoot);
55
+ return resolved;
56
+ }
57
+
58
+ /**
59
+ * Options for configuring path validation behavior.
60
+ */
61
+ export interface PathValidationOptions {
62
+ /**
63
+ * The root directory that all paths must be contained within.
64
+ * Defaults to process.cwd() if not specified.
65
+ */
66
+ allowedRoot?: string;
67
+ }
68
+
69
+ /**
70
+ * Get the allowed root directory from options or environment.
71
+ * Checks MLX_NODE_DATA_ROOT environment variable first, then falls back to cwd.
72
+ *
73
+ * @param options - Optional validation options
74
+ * @returns The allowed root directory path
75
+ */
76
+ export function getAllowedRoot(options?: PathValidationOptions): string {
77
+ if (options?.allowedRoot) {
78
+ return options.allowedRoot;
79
+ }
80
+
81
+ // Check environment variable for configurable data root
82
+ const envRoot = process.env['MLX_NODE_DATA_ROOT'];
83
+ if (envRoot) {
84
+ return resolvePath(envRoot);
85
+ }
86
+
87
+ return process.cwd();
88
+ }
@@ -0,0 +1,209 @@
1
+ import { type XmlParseResult } from '../types.js';
2
+
3
+ const REASONING_OPEN = '<reasoning>';
4
+ const REASONING_CLOSE = '</reasoning>';
5
+ const ANSWER_OPEN = '<answer>';
6
+ const ANSWER_CLOSE = '</answer>';
7
+
8
+ type ParserState =
9
+ | 'searchReasoningOpen'
10
+ | 'readReasoning'
11
+ | 'searchAnswerOpen'
12
+ | 'readAnswer'
13
+ | 'consumeTrailing'
14
+ | 'done';
15
+
16
+ function isWhitespace(char: string): boolean {
17
+ return char === ' ' || char === '\n' || char === '\r' || char === '\t' || char === '\f' || char === '\v';
18
+ }
19
+
20
+ function sliceWithTag(text: string, openTag: string, closeTag: string): string | null {
21
+ const openIndex = text.indexOf(openTag);
22
+ if (openIndex === -1) return null;
23
+ const start = openIndex + openTag.length;
24
+ const closeIndex = text.indexOf(closeTag, start);
25
+ if (closeIndex === -1) return null;
26
+ return text.slice(start, closeIndex).trim();
27
+ }
28
+
29
+ export function parseXmlCot(content: string): XmlParseResult {
30
+ const text = content ?? '';
31
+ const errors: string[] = [];
32
+
33
+ let state: ParserState = 'searchReasoningOpen';
34
+ let index = 0;
35
+ const length = text.length;
36
+
37
+ let reasoning: string | null = null;
38
+ let answer: string | null = null;
39
+
40
+ let reasoningFound = false;
41
+ let answerFound = false;
42
+ let reasoningClosed = false;
43
+ let answerClosed = false;
44
+
45
+ let hasLeadingText = false;
46
+ let hasBetweenText = false;
47
+ let hasTrailingText = false;
48
+
49
+ let usedFallbackReasoning = false;
50
+ let usedFallbackAnswer = false;
51
+
52
+ while (state !== 'done') {
53
+ switch (state) {
54
+ case 'searchReasoningOpen': {
55
+ while (index < length) {
56
+ const char = text[index];
57
+ if (isWhitespace(char)) {
58
+ index += 1;
59
+ continue;
60
+ }
61
+ if (text.startsWith(REASONING_OPEN, index)) {
62
+ reasoningFound = true;
63
+ index += REASONING_OPEN.length;
64
+ state = 'readReasoning';
65
+ break;
66
+ }
67
+ hasLeadingText = true;
68
+ index += 1;
69
+ }
70
+ if (state === 'searchReasoningOpen') {
71
+ state = 'done';
72
+ }
73
+ break;
74
+ }
75
+ case 'readReasoning': {
76
+ const closingIndex = text.indexOf(REASONING_CLOSE, index);
77
+ if (closingIndex === -1) {
78
+ reasoning = text.slice(index).trim() || null;
79
+ errors.push('Unterminated <reasoning>...</reasoning> section.');
80
+ state = 'done';
81
+ break;
82
+ }
83
+ reasoning = text.slice(index, closingIndex).trim();
84
+ reasoningClosed = true;
85
+ index = closingIndex + REASONING_CLOSE.length;
86
+ state = 'searchAnswerOpen';
87
+ break;
88
+ }
89
+ case 'searchAnswerOpen': {
90
+ while (index < length) {
91
+ const char = text[index];
92
+ if (isWhitespace(char)) {
93
+ index += 1;
94
+ continue;
95
+ }
96
+ if (text.startsWith(ANSWER_OPEN, index)) {
97
+ answerFound = true;
98
+ index += ANSWER_OPEN.length;
99
+ state = 'readAnswer';
100
+ break;
101
+ }
102
+ hasBetweenText = true;
103
+ index += 1;
104
+ }
105
+ if (state === 'searchAnswerOpen') {
106
+ state = 'done';
107
+ }
108
+ break;
109
+ }
110
+ case 'readAnswer': {
111
+ const closingIndex = text.indexOf(ANSWER_CLOSE, index);
112
+ if (closingIndex === -1) {
113
+ answer = text.slice(index).trim() || null;
114
+ errors.push('Unterminated <answer>...</answer> section.');
115
+ state = 'done';
116
+ break;
117
+ }
118
+ answer = text.slice(index, closingIndex).trim();
119
+ answerClosed = true;
120
+ index = closingIndex + ANSWER_CLOSE.length;
121
+ state = 'consumeTrailing';
122
+ break;
123
+ }
124
+ case 'consumeTrailing': {
125
+ while (index < length) {
126
+ const char = text[index];
127
+ if (!isWhitespace(char)) {
128
+ hasTrailingText = true;
129
+ }
130
+ index += 1;
131
+ }
132
+ state = 'done';
133
+ break;
134
+ }
135
+ }
136
+ }
137
+
138
+ if (!reasoningFound) {
139
+ const fallback = sliceWithTag(text, REASONING_OPEN, REASONING_CLOSE);
140
+ if (fallback !== null) {
141
+ reasoning = fallback;
142
+ reasoningFound = true;
143
+ reasoningClosed = true;
144
+ usedFallbackReasoning = true;
145
+ }
146
+ }
147
+
148
+ if (!answerFound) {
149
+ const fallback = sliceWithTag(text, ANSWER_OPEN, ANSWER_CLOSE);
150
+ if (fallback !== null) {
151
+ answer = fallback;
152
+ answerFound = true;
153
+ answerClosed = true;
154
+ usedFallbackAnswer = true;
155
+ }
156
+ }
157
+
158
+ if (!reasoningFound) {
159
+ errors.push('Missing <reasoning>...</reasoning> section.');
160
+ }
161
+ if (!answerFound) {
162
+ errors.push('Missing <answer>...</answer> section.');
163
+ }
164
+
165
+ if (hasLeadingText) {
166
+ errors.push('XML format contains extra characters before <reasoning> section.');
167
+ }
168
+ if (hasBetweenText) {
169
+ errors.push('XML format contains extra characters between reasoning and answer sections.');
170
+ }
171
+ if (hasTrailingText) {
172
+ errors.push('XML format contains extra characters after </answer> section.');
173
+ }
174
+
175
+ const isSoftMatch = reasoningFound && answerFound && reasoningClosed && answerClosed;
176
+ const isStrictMatch =
177
+ isSoftMatch &&
178
+ !hasLeadingText &&
179
+ !hasBetweenText &&
180
+ !hasTrailingText &&
181
+ !usedFallbackReasoning &&
182
+ !usedFallbackAnswer;
183
+
184
+ return {
185
+ reasoning: reasoning ?? null,
186
+ answer: answer ?? null,
187
+ isStrictMatch,
188
+ isSoftMatch,
189
+ errors,
190
+ };
191
+ }
192
+
193
+ export function extractXmlAnswer(content: string): string | null {
194
+ const { answer } = parseXmlCot(content);
195
+ return answer;
196
+ }
197
+
198
+ export function extractXmlReasoning(content: string): string | null {
199
+ const { reasoning } = parseXmlCot(content);
200
+ return reasoning;
201
+ }
202
+
203
+ export function extractHashAnswer(text: string): string | null {
204
+ if (!text) return null;
205
+ const separator = text.indexOf('####');
206
+ if (separator === -1) return null;
207
+ const extracted = text.slice(separator + 4).trim();
208
+ return extracted.length ? extracted : null;
209
+ }