@mlx-node/trl 0.0.0

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.
Files changed (37) hide show
  1. package/dist/data/dataset.d.ts +22 -0
  2. package/dist/data/dataset.d.ts.map +1 -0
  3. package/dist/data/dataset.js +142 -0
  4. package/dist/data/sft-dataset.d.ts +156 -0
  5. package/dist/data/sft-dataset.d.ts.map +1 -0
  6. package/dist/data/sft-dataset.js +415 -0
  7. package/dist/index.d.ts +33 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +47 -0
  10. package/dist/trainers/grpo-config.d.ts +42 -0
  11. package/dist/trainers/grpo-config.d.ts.map +1 -0
  12. package/dist/trainers/grpo-config.js +220 -0
  13. package/dist/trainers/grpo-entropy.d.ts +33 -0
  14. package/dist/trainers/grpo-entropy.d.ts.map +1 -0
  15. package/dist/trainers/grpo-entropy.js +18 -0
  16. package/dist/trainers/grpo-trainer.d.ts +602 -0
  17. package/dist/trainers/grpo-trainer.d.ts.map +1 -0
  18. package/dist/trainers/grpo-trainer.js +1439 -0
  19. package/dist/trainers/sft-config.d.ts +32 -0
  20. package/dist/trainers/sft-config.d.ts.map +1 -0
  21. package/dist/trainers/sft-config.js +186 -0
  22. package/dist/trainers/sft-trainer.d.ts +141 -0
  23. package/dist/trainers/sft-trainer.d.ts.map +1 -0
  24. package/dist/trainers/sft-trainer.js +502 -0
  25. package/dist/trainers/training-logger.d.ts +375 -0
  26. package/dist/trainers/training-logger.d.ts.map +1 -0
  27. package/dist/trainers/training-logger.js +542 -0
  28. package/dist/types.d.ts +54 -0
  29. package/dist/types.d.ts.map +1 -0
  30. package/dist/types.js +1 -0
  31. package/dist/utils/path-security.d.ts +51 -0
  32. package/dist/utils/path-security.d.ts.map +1 -0
  33. package/dist/utils/path-security.js +69 -0
  34. package/dist/utils/xml-parser.d.ts +6 -0
  35. package/dist/utils/xml-parser.d.ts.map +1 -0
  36. package/dist/utils/xml-parser.js +184 -0
  37. package/package.json +29 -0
@@ -0,0 +1,69 @@
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
+ import { resolve as resolvePath, normalize, relative, isAbsolute } from 'node:path';
8
+ /**
9
+ * Error thrown when a path traversal attempt is detected.
10
+ */
11
+ export class PathTraversalError extends Error {
12
+ resolvedPath;
13
+ allowedRoot;
14
+ constructor(resolvedPath, allowedRoot) {
15
+ super(`Path traversal detected: "${resolvedPath}" is outside allowed directory "${allowedRoot}"`);
16
+ this.resolvedPath = resolvedPath;
17
+ this.allowedRoot = allowedRoot;
18
+ this.name = 'PathTraversalError';
19
+ }
20
+ }
21
+ /**
22
+ * Validates that a resolved path is contained within an allowed root directory.
23
+ * Prevents path traversal attacks via '../' sequences.
24
+ *
25
+ * @param resolvedPath - The fully resolved absolute path to validate
26
+ * @param allowedRoot - The root directory that paths must be contained within
27
+ * @throws PathTraversalError if path escapes the allowed root
28
+ */
29
+ export function validatePathContainment(resolvedPath, allowedRoot) {
30
+ const normalizedPath = normalize(resolvedPath);
31
+ const normalizedRoot = normalize(allowedRoot);
32
+ // Get relative path from root to target
33
+ const relativePath = relative(normalizedRoot, normalizedPath);
34
+ // If relative path starts with '..' or is absolute, it's outside the root
35
+ if (relativePath.startsWith('..') || isAbsolute(relativePath)) {
36
+ throw new PathTraversalError(resolvedPath, allowedRoot);
37
+ }
38
+ }
39
+ /**
40
+ * Resolves a user-provided path and validates it stays within an allowed root.
41
+ *
42
+ * @param userPath - The user-provided path (may be relative or absolute)
43
+ * @param allowedRoot - The root directory that the path must be contained within
44
+ * @returns The resolved absolute path
45
+ * @throws PathTraversalError if the resolved path escapes the allowed root
46
+ */
47
+ export function resolveAndValidatePath(userPath, allowedRoot) {
48
+ const resolved = resolvePath(allowedRoot, userPath);
49
+ validatePathContainment(resolved, allowedRoot);
50
+ return resolved;
51
+ }
52
+ /**
53
+ * Get the allowed root directory from options or environment.
54
+ * Checks MLX_NODE_DATA_ROOT environment variable first, then falls back to cwd.
55
+ *
56
+ * @param options - Optional validation options
57
+ * @returns The allowed root directory path
58
+ */
59
+ export function getAllowedRoot(options) {
60
+ if (options?.allowedRoot) {
61
+ return options.allowedRoot;
62
+ }
63
+ // Check environment variable for configurable data root
64
+ const envRoot = process.env['MLX_NODE_DATA_ROOT'];
65
+ if (envRoot) {
66
+ return resolvePath(envRoot);
67
+ }
68
+ return process.cwd();
69
+ }
@@ -0,0 +1,6 @@
1
+ import { type XmlParseResult } from '../types';
2
+ export declare function parseXmlCot(content: string): XmlParseResult;
3
+ export declare function extractXmlAnswer(content: string): string | null;
4
+ export declare function extractXmlReasoning(content: string): string | null;
5
+ export declare function extractHashAnswer(text: string): string | null;
6
+ //# sourceMappingURL=xml-parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xml-parser.d.ts","sourceRoot":"","sources":["../../src/utils/xml-parser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AA4B/C,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,CAkK3D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAG/D;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAGlE;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM7D"}
@@ -0,0 +1,184 @@
1
+ const REASONING_OPEN = '<reasoning>';
2
+ const REASONING_CLOSE = '</reasoning>';
3
+ const ANSWER_OPEN = '<answer>';
4
+ const ANSWER_CLOSE = '</answer>';
5
+ function isWhitespace(char) {
6
+ return char === ' ' || char === '\n' || char === '\r' || char === '\t' || char === '\f' || char === '\v';
7
+ }
8
+ function sliceWithTag(text, openTag, closeTag) {
9
+ const openIndex = text.indexOf(openTag);
10
+ if (openIndex === -1)
11
+ return null;
12
+ const start = openIndex + openTag.length;
13
+ const closeIndex = text.indexOf(closeTag, start);
14
+ if (closeIndex === -1)
15
+ return null;
16
+ return text.slice(start, closeIndex).trim();
17
+ }
18
+ export function parseXmlCot(content) {
19
+ const text = content ?? '';
20
+ const errors = [];
21
+ let state = 'searchReasoningOpen';
22
+ let index = 0;
23
+ const length = text.length;
24
+ let reasoning = null;
25
+ let answer = null;
26
+ let reasoningFound = false;
27
+ let answerFound = false;
28
+ let reasoningClosed = false;
29
+ let answerClosed = false;
30
+ let hasLeadingText = false;
31
+ let hasBetweenText = false;
32
+ let hasTrailingText = false;
33
+ let usedFallbackReasoning = false;
34
+ let usedFallbackAnswer = false;
35
+ while (state !== 'done') {
36
+ switch (state) {
37
+ case 'searchReasoningOpen': {
38
+ while (index < length) {
39
+ const char = text[index];
40
+ if (isWhitespace(char)) {
41
+ index += 1;
42
+ continue;
43
+ }
44
+ if (text.startsWith(REASONING_OPEN, index)) {
45
+ reasoningFound = true;
46
+ index += REASONING_OPEN.length;
47
+ state = 'readReasoning';
48
+ break;
49
+ }
50
+ hasLeadingText = true;
51
+ index += 1;
52
+ }
53
+ if (state === 'searchReasoningOpen') {
54
+ state = 'done';
55
+ }
56
+ break;
57
+ }
58
+ case 'readReasoning': {
59
+ const closingIndex = text.indexOf(REASONING_CLOSE, index);
60
+ if (closingIndex === -1) {
61
+ reasoning = text.slice(index).trim() || null;
62
+ errors.push('Unterminated <reasoning>...</reasoning> section.');
63
+ state = 'done';
64
+ break;
65
+ }
66
+ reasoning = text.slice(index, closingIndex).trim();
67
+ reasoningClosed = true;
68
+ index = closingIndex + REASONING_CLOSE.length;
69
+ state = 'searchAnswerOpen';
70
+ break;
71
+ }
72
+ case 'searchAnswerOpen': {
73
+ while (index < length) {
74
+ const char = text[index];
75
+ if (isWhitespace(char)) {
76
+ index += 1;
77
+ continue;
78
+ }
79
+ if (text.startsWith(ANSWER_OPEN, index)) {
80
+ answerFound = true;
81
+ index += ANSWER_OPEN.length;
82
+ state = 'readAnswer';
83
+ break;
84
+ }
85
+ hasBetweenText = true;
86
+ index += 1;
87
+ }
88
+ if (state === 'searchAnswerOpen') {
89
+ state = 'done';
90
+ }
91
+ break;
92
+ }
93
+ case 'readAnswer': {
94
+ const closingIndex = text.indexOf(ANSWER_CLOSE, index);
95
+ if (closingIndex === -1) {
96
+ answer = text.slice(index).trim() || null;
97
+ errors.push('Unterminated <answer>...</answer> section.');
98
+ state = 'done';
99
+ break;
100
+ }
101
+ answer = text.slice(index, closingIndex).trim();
102
+ answerClosed = true;
103
+ index = closingIndex + ANSWER_CLOSE.length;
104
+ state = 'consumeTrailing';
105
+ break;
106
+ }
107
+ case 'consumeTrailing': {
108
+ while (index < length) {
109
+ const char = text[index];
110
+ if (!isWhitespace(char)) {
111
+ hasTrailingText = true;
112
+ }
113
+ index += 1;
114
+ }
115
+ state = 'done';
116
+ break;
117
+ }
118
+ }
119
+ }
120
+ if (!reasoningFound) {
121
+ const fallback = sliceWithTag(text, REASONING_OPEN, REASONING_CLOSE);
122
+ if (fallback !== null) {
123
+ reasoning = fallback;
124
+ reasoningFound = true;
125
+ reasoningClosed = true;
126
+ usedFallbackReasoning = true;
127
+ }
128
+ }
129
+ if (!answerFound) {
130
+ const fallback = sliceWithTag(text, ANSWER_OPEN, ANSWER_CLOSE);
131
+ if (fallback !== null) {
132
+ answer = fallback;
133
+ answerFound = true;
134
+ answerClosed = true;
135
+ usedFallbackAnswer = true;
136
+ }
137
+ }
138
+ if (!reasoningFound) {
139
+ errors.push('Missing <reasoning>...</reasoning> section.');
140
+ }
141
+ if (!answerFound) {
142
+ errors.push('Missing <answer>...</answer> section.');
143
+ }
144
+ if (hasLeadingText) {
145
+ errors.push('XML format contains extra characters before <reasoning> section.');
146
+ }
147
+ if (hasBetweenText) {
148
+ errors.push('XML format contains extra characters between reasoning and answer sections.');
149
+ }
150
+ if (hasTrailingText) {
151
+ errors.push('XML format contains extra characters after </answer> section.');
152
+ }
153
+ const isSoftMatch = reasoningFound && answerFound && reasoningClosed && answerClosed;
154
+ const isStrictMatch = isSoftMatch &&
155
+ !hasLeadingText &&
156
+ !hasBetweenText &&
157
+ !hasTrailingText &&
158
+ !usedFallbackReasoning &&
159
+ !usedFallbackAnswer;
160
+ return {
161
+ reasoning: reasoning ?? null,
162
+ answer: answer ?? null,
163
+ isStrictMatch,
164
+ isSoftMatch,
165
+ errors,
166
+ };
167
+ }
168
+ export function extractXmlAnswer(content) {
169
+ const { answer } = parseXmlCot(content);
170
+ return answer;
171
+ }
172
+ export function extractXmlReasoning(content) {
173
+ const { reasoning } = parseXmlCot(content);
174
+ return reasoning;
175
+ }
176
+ export function extractHashAnswer(text) {
177
+ if (!text)
178
+ return null;
179
+ const separator = text.indexOf('####');
180
+ if (separator === -1)
181
+ return null;
182
+ const extracted = text.slice(separator + 4).trim();
183
+ return extracted.length ? extracted : null;
184
+ }
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@mlx-node/trl",
3
+ "version": "0.0.0",
4
+ "files": [
5
+ "dist"
6
+ ],
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "scripts": {
17
+ "build": "tsc -b",
18
+ "test": "vite test run",
19
+ "test:trainer": "TEST_TRAINER=1 vite test run"
20
+ },
21
+ "dependencies": {
22
+ "@mlx-node/core": "0.0.0",
23
+ "@mlx-node/lm": "0.0.0",
24
+ "@std/toml": "npm:@jsr/std__toml@^1.0.11"
25
+ },
26
+ "devDependencies": {
27
+ "@huggingface/hub": "^2.7.1"
28
+ }
29
+ }