@swapai/core 0.1.0 → 0.2.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.
@@ -24,6 +24,7 @@ type ReferenceClassifier<Result extends ResultValue> = (input: string) => Result
24
24
  interface Classifier<Result extends ResultValue> {
25
25
  isTrained(): boolean;
26
26
  logClassification(input: string, result: Result): void;
27
+ clearTrainingData(): void;
27
28
  classify(input: string, referenceClassifier?: ReferenceClassifier<Result>): Promise<Result>;
28
29
  flush(): Promise<void>;
29
30
  close(): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swapai/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Replace paid classifiers with locally trained Needle 2 classifiers.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -4,8 +4,10 @@ from __future__ import annotations
4
4
  import argparse
5
5
  import json
6
6
  import os
7
+ import sqlite3
7
8
  import sys
8
9
  import types
10
+ from contextlib import contextmanager
9
11
  from pathlib import Path
10
12
  from typing import Any
11
13
 
@@ -28,52 +30,78 @@ def require_version(needle: Any) -> None:
28
30
  )
29
31
 
30
32
 
31
- def train(args: argparse.Namespace) -> None:
32
- import needle
33
- from needle.model.finetune import build_main, finetune_local
33
+ @contextmanager
34
+ def artifact_write_lock(args: argparse.Namespace):
35
+ lock_database = sqlite3.connect(args.artifact_lock_database, timeout=30)
36
+ main_database: sqlite3.Connection | None = None
37
+ try:
38
+ lock_database.execute("BEGIN IMMEDIATE")
39
+ main_database = sqlite3.connect(f"file:{args.main_database}?mode=ro", uri=True)
40
+ row = main_database.execute(
41
+ "SELECT data_epoch, clear_pending FROM classifiers WHERE name = ?",
42
+ (args.classifier_name,),
43
+ ).fetchone()
44
+ if row is None or row[0] != args.expected_epoch or row[1] != 0:
45
+ raise RuntimeError("Classifier training was superseded by data erasure")
46
+ yield
47
+ finally:
48
+ if main_database is not None:
49
+ main_database.close()
50
+ try:
51
+ lock_database.rollback()
52
+ finally:
53
+ lock_database.close()
34
54
 
35
- require_version(needle)
36
- checkpoint_dir = Path(args.checkpoint_dir).resolve()
37
- checkpoint_dir.mkdir(parents=True, exist_ok=True)
38
- checkpoint = checkpoint_dir / "needle2.pkl"
39
- output = Path(args.output).resolve()
40
- output.parent.mkdir(parents=True, exist_ok=True)
41
- adapter = output.parent / "swapai-lora.pkl"
42
- with open(args.training_data, "r", encoding="utf-8") as handle:
43
- example_count = sum(1 for line in handle if line.strip())
44
- batch_size = min(16, max(1, (example_count + 9) // 10))
45
-
46
- finetune_local(
47
- types.SimpleNamespace(
48
- jsonl_path=str(Path(args.training_data).resolve()),
49
- checkpoint=str(checkpoint),
50
- epochs=args.epochs,
51
- batch_size=batch_size,
52
- lr=1e-4,
53
- lora_rank=16,
54
- lora_alpha=32.0,
55
- max_len=1024,
56
- val_split=0.0,
57
- seed=0,
58
- generate=0,
59
- model="deepseek/deepseek-v4-flash",
60
- workers=1,
61
- checkpoint_dir=str(checkpoint_dir),
62
- out=str(adapter),
63
- qat_bits="auto",
55
+
56
+ def train(args: argparse.Namespace) -> None:
57
+ with artifact_write_lock(args):
58
+ import needle
59
+ from needle.model.finetune import build_main, finetune_local
60
+
61
+ require_version(needle)
62
+ checkpoint_dir = Path(args.checkpoint_dir).resolve()
63
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
64
+ checkpoint = checkpoint_dir / "needle2.pkl"
65
+ output = Path(args.output).resolve()
66
+ output.parent.mkdir(parents=True, exist_ok=True)
67
+ training_data = Path(args.training_data).resolve()
68
+ training_data.write_text(sys.stdin.read(), encoding="utf-8")
69
+ adapter = output.parent / "swapai-lora.pkl"
70
+ with training_data.open("r", encoding="utf-8") as handle:
71
+ example_count = sum(1 for line in handle if line.strip())
72
+ batch_size = min(16, max(1, (example_count + 9) // 10))
73
+
74
+ finetune_local(
75
+ types.SimpleNamespace(
76
+ jsonl_path=str(training_data),
77
+ checkpoint=str(checkpoint),
78
+ epochs=args.epochs,
79
+ batch_size=batch_size,
80
+ lr=1e-4,
81
+ lora_rank=16,
82
+ lora_alpha=32.0,
83
+ max_len=1024,
84
+ val_split=0.0,
85
+ seed=0,
86
+ generate=0,
87
+ model="deepseek/deepseek-v4-flash",
88
+ workers=1,
89
+ checkpoint_dir=str(checkpoint_dir),
90
+ out=str(adapter),
91
+ qat_bits="auto",
92
+ )
64
93
  )
65
- )
66
- build_main(
67
- types.SimpleNamespace(
68
- checkpoint=str(checkpoint),
69
- lora=str(adapter),
70
- out=str(output),
71
- upload=False,
72
- bits=None,
94
+ build_main(
95
+ types.SimpleNamespace(
96
+ checkpoint=str(checkpoint),
97
+ lora=str(adapter),
98
+ out=str(output),
99
+ upload=False,
100
+ bits=None,
101
+ )
73
102
  )
74
- )
75
- if not output.is_file():
76
- raise RuntimeError("Needle did not create the requested .cact model")
103
+ if not output.is_file():
104
+ raise RuntimeError("Needle did not create the requested .cact model")
77
105
 
78
106
 
79
107
  def classification_result(response: Any) -> Any:
@@ -147,6 +175,10 @@ def parser() -> argparse.ArgumentParser:
147
175
  train_parser.add_argument("--output", required=True)
148
176
  train_parser.add_argument("--checkpoint-dir", required=True)
149
177
  train_parser.add_argument("--epochs", type=int, default=10)
178
+ train_parser.add_argument("--artifact-lock-database", required=True)
179
+ train_parser.add_argument("--main-database", required=True)
180
+ train_parser.add_argument("--classifier-name", required=True)
181
+ train_parser.add_argument("--expected-epoch", type=int, required=True)
150
182
 
151
183
  serve_parser = commands.add_parser("serve")
152
184
  serve_parser.add_argument("--model", required=True)