wleno 0.1.0__tar.gz

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.
wleno-0.1.0/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ 저작권 안내 (All Rights Reserved)
2
+
3
+ Copyright (c) 2026 gbox3d
4
+
5
+ 이 저장소의 교재, 문서, 슬라이드 원고, 강의 대본, 실습 자료와 예제 코드의
6
+ 저작권은 저작권자에게 있습니다.
7
+
8
+ 허용되는 이용:
9
+ - 수업 수강과 개인 학습 목적의 열람, 클론, 로컬 실행
10
+
11
+ 금지되는 이용 (저작권자의 사전 서면 허락이 필요합니다):
12
+ - 전체 또는 일부의 무단 재배포, 전재, 재게시, 미러링
13
+ - 상업적 이용
14
+ - 2차 저작물의 제작과 배포
15
+
16
+ 이 저장소가 GitHub에 공개되어 있는 것은 수강생의 접근 편의를 위한 것이며,
17
+ 오픈소스 라이선스의 부여를 의미하지 않습니다.
wleno-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: wleno
3
+ Version: 0.1.0
4
+ Summary: WlEno teaching board simulator and Python control library
5
+ License-Expression: LicenseRef-Proprietary
6
+ Project-URL: Source, https://github.com/gbox3d/teaching_repo/tree/main/tools/wleno
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Provides-Extra: needle
11
+ Requires-Dist: cactus-compute==4.2.0; extra == "needle"
12
+ Provides-Extra: train
13
+ Requires-Dist: cactus-compute[train]==4.2.0; extra == "train"
14
+ Dynamic: license-file
15
+
16
+ WlEno는 LED와 온습도 센서를 갖춘 가상 보드다. Python 3.10 이상에서 uv 프로젝트를 열고 시뮬레이터를 실행한다.
17
+
18
+ ```shell
19
+ uv add wleno
20
+ uv run wleno --bind 127.0.0.1
21
+ ```
22
+
23
+ 창 없이 실행하려면 마지막 명령에 `--no-window`를 붙인다. 시뮬레이터를 실행한 상태에서 같은 프로젝트의 Python 코드로 보드 상태를 읽을 수 있다.
24
+
25
+ ```python
26
+ from wleno.control import Board
27
+
28
+ with Board() as board:
29
+ print(board.state())
30
+ ```
31
+
32
+ [10주차 실습 ZIP 설치 안내](https://github.com/gbox3d/teaching_repo/blob/main/open_source_ai/weeks/week10_simulator_control/distribution/README.md)
@@ -0,0 +1,138 @@
1
+ """10~13주차가 같은 연결·검증·평가 함수를 사용한다."""
2
+
3
+ import json
4
+ import socket
5
+ from contextlib import suppress
6
+ from pathlib import Path
7
+ from urllib.request import ProxyHandler, Request, build_opener
8
+
9
+ DATA_DIR = Path(__file__).parent / "data"
10
+
11
+
12
+ def http_json(url, body=None, timeout=30):
13
+ data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
14
+ request = Request(url, data=data, headers={"Content-Type": "application/json"})
15
+ with build_opener(ProxyHandler({})).open(request, timeout=timeout) as response:
16
+ return json.load(response)
17
+
18
+
19
+ def validate_calls(calls):
20
+ """전체 목록을 먼저 검사한다. 잘못된 뒤쪽 호출 때문에 앞쪽만 실행하지 않는다."""
21
+ if not isinstance(calls, list) or len(calls) > 8:
22
+ raise ValueError("호출 목록은 최대 8개여야 합니다.")
23
+ fields = {"turn_on": {"index"}, "turn_off": {"index"},
24
+ "set_brightness": {"index", "value"}, "read_environment": set()}
25
+ for call in calls:
26
+ if not isinstance(call, dict) or set(call) != {"name", "arguments"}:
27
+ raise ValueError("호출에는 name과 arguments가 필요합니다.")
28
+ name, args = call["name"], call["arguments"]
29
+ if not isinstance(name, str) or name not in fields:
30
+ raise ValueError("등록되지 않은 함수입니다.")
31
+ if not isinstance(args, dict) or set(args) != fields[name]:
32
+ raise ValueError("함수의 필수 인자가 없거나 다른 인자가 있습니다.")
33
+ for key, high in (("index", 3), ("value", 255)):
34
+ if key in args and (type(args[key]) is not int or not 0 <= args[key] <= high):
35
+ raise ValueError(f"{key}는 0~{high} 범위의 정수여야 합니다.")
36
+ return calls
37
+
38
+
39
+ class Board:
40
+ """한 실습 동안 유지하는 TCP 연결. 닫아도 WlEno의 보드 상태는 유지된다."""
41
+
42
+ def __init__(self, host="127.0.0.1", port=8266, http_url="http://127.0.0.1:8080"):
43
+ self.http_url = http_url
44
+ self.closed = False
45
+ self.socket = socket.create_connection((host, port), timeout=5)
46
+ self.file = self.socket.makefile("rw", encoding="utf-8", newline="\n")
47
+ try:
48
+ hello = json.loads(self.file.readline())
49
+ if hello.get("event") != "hello":
50
+ raise ValueError("시뮬레이터의 시작 응답을 확인할 수 없습니다.")
51
+ except BaseException:
52
+ self.close()
53
+ raise
54
+
55
+ def command(self, text):
56
+ if getattr(self, "closed", False):
57
+ raise ConnectionError("연결이 닫혔습니다. 시뮬레이터에 다시 연결하세요.")
58
+ try:
59
+ self.file.write(text + "\n")
60
+ self.file.flush()
61
+ # 입력 버튼 이벤트가 명령 응답보다 먼저 도착할 수 있다.
62
+ for _ in range(32):
63
+ line = self.file.readline()
64
+ if not line:
65
+ raise ConnectionError("시뮬레이터 연결이 종료되었습니다.")
66
+ reply = json.loads(line)
67
+ if "event" not in reply:
68
+ if reply.get("result") != "ok":
69
+ raise RuntimeError(f"시뮬레이터 명령 실패: {reply}")
70
+ return reply
71
+ raise ConnectionError("이벤트가 계속 도착해 연결을 닫았습니다. 다시 연결하세요.")
72
+ except BaseException:
73
+ # 응답 순서를 보장할 수 없는 연결을 다음 요청에 재사용하지 않는다.
74
+ self.close()
75
+ raise
76
+
77
+ def execute(self, calls):
78
+ validate_calls(calls)
79
+ results = []
80
+ for call in calls:
81
+ name, args = call["name"], call["arguments"]
82
+ if name == "read_environment":
83
+ command = "dht11"
84
+ elif name == "set_brightness":
85
+ command = f"pwm {args['index']} {args['value']}"
86
+ else:
87
+ command = f"{'on' if name == 'turn_on' else 'off'} {args['index']}"
88
+ results.append(self.command(command))
89
+ return results
90
+
91
+ def state(self):
92
+ if getattr(self, "closed", False):
93
+ raise ConnectionError("연결이 닫혔습니다. 시뮬레이터에 다시 연결하세요.")
94
+ return http_json(self.http_url + "/state", timeout=5)
95
+
96
+ def close(self):
97
+ if not getattr(self, "closed", False):
98
+ self.closed = True
99
+ with suppress(OSError):
100
+ self.file.close()
101
+ with suppress(OSError):
102
+ self.socket.close()
103
+
104
+ def __enter__(self):
105
+ return self
106
+
107
+ def __exit__(self, *args):
108
+ self.close()
109
+
110
+
111
+ def load_cases():
112
+ return json.loads((DATA_DIR / "control_cases.json").read_text(encoding="utf-8"))
113
+
114
+
115
+ def chat(predict, board):
116
+ print("제어 요청을 입력하세요. /bye 또는 Ctrl+C로 종료합니다.")
117
+ while True:
118
+ try:
119
+ question = input("요청> ").strip()
120
+ if question == "/bye":
121
+ break
122
+ if not question:
123
+ continue
124
+ calls = predict(question)
125
+ print("호출:", json.dumps(calls, ensure_ascii=False))
126
+ if calls:
127
+ print("응답:", board.execute(calls))
128
+ else:
129
+ print("실행할 호출이 없습니다.")
130
+ print("LED:", board.state()["leds"])
131
+ except (EOFError, KeyboardInterrupt):
132
+ print("\n대화를 종료합니다.")
133
+ break
134
+ except Exception as error:
135
+ print(f"오류: {error}")
136
+ if board.closed:
137
+ print("연결이 닫혔습니다. 프로그램을 다시 실행하세요.")
138
+ break
@@ -0,0 +1,179 @@
1
+ [
2
+ {
3
+ "id": "control-01",
4
+ "language": "ko",
5
+ "query": "0번 LED를 켜 주세요",
6
+ "calls": [
7
+ {
8
+ "name": "turn_on",
9
+ "arguments": {
10
+ "index": 0
11
+ }
12
+ }
13
+ ]
14
+ },
15
+ {
16
+ "id": "control-02",
17
+ "language": "ko",
18
+ "query": "불이 켜진 3번 LED를 꺼 줘",
19
+ "calls": [
20
+ {
21
+ "name": "turn_off",
22
+ "arguments": {
23
+ "index": 3
24
+ }
25
+ }
26
+ ]
27
+ },
28
+ {
29
+ "id": "control-03",
30
+ "language": "ko",
31
+ "query": "2번 LED 밝기를 75로 맞춰 줘",
32
+ "calls": [
33
+ {
34
+ "name": "set_brightness",
35
+ "arguments": {
36
+ "index": 2,
37
+ "value": 75
38
+ }
39
+ }
40
+ ]
41
+ },
42
+ {
43
+ "id": "control-04",
44
+ "language": "ko",
45
+ "query": "지금 온도와 습도를 읽어 주세요",
46
+ "calls": [
47
+ {
48
+ "name": "read_environment",
49
+ "arguments": {}
50
+ }
51
+ ]
52
+ },
53
+ {
54
+ "id": "control-05",
55
+ "language": "en",
56
+ "query": "Switch LED 1 on.",
57
+ "calls": [
58
+ {
59
+ "name": "turn_on",
60
+ "arguments": {
61
+ "index": 1
62
+ }
63
+ }
64
+ ]
65
+ },
66
+ {
67
+ "id": "control-06",
68
+ "language": "en",
69
+ "query": "Please switch off LED 2.",
70
+ "calls": [
71
+ {
72
+ "name": "turn_off",
73
+ "arguments": {
74
+ "index": 2
75
+ }
76
+ }
77
+ ]
78
+ },
79
+ {
80
+ "id": "control-07",
81
+ "language": "en",
82
+ "query": "Set LED 0 brightness to 180.",
83
+ "calls": [
84
+ {
85
+ "name": "set_brightness",
86
+ "arguments": {
87
+ "index": 0,
88
+ "value": 180
89
+ }
90
+ }
91
+ ]
92
+ },
93
+ {
94
+ "id": "control-08",
95
+ "language": "en",
96
+ "query": "Read the current temperature and humidity.",
97
+ "calls": [
98
+ {
99
+ "name": "read_environment",
100
+ "arguments": {}
101
+ }
102
+ ]
103
+ },
104
+ {
105
+ "id": "control-09",
106
+ "language": "ko",
107
+ "query": "1번을 켜고 3번 LED를 꺼 주세요",
108
+ "calls": [
109
+ {
110
+ "name": "turn_on",
111
+ "arguments": {
112
+ "index": 1
113
+ }
114
+ },
115
+ {
116
+ "name": "turn_off",
117
+ "arguments": {
118
+ "index": 3
119
+ }
120
+ }
121
+ ]
122
+ },
123
+ {
124
+ "id": "control-10",
125
+ "language": "en",
126
+ "query": "Turn LED 2 off, then set LED 1 to brightness 90.",
127
+ "calls": [
128
+ {
129
+ "name": "turn_off",
130
+ "arguments": {
131
+ "index": 2
132
+ }
133
+ },
134
+ {
135
+ "name": "set_brightness",
136
+ "arguments": {
137
+ "index": 1,
138
+ "value": 90
139
+ }
140
+ }
141
+ ]
142
+ },
143
+ {
144
+ "id": "control-11",
145
+ "language": "ko",
146
+ "query": "그 불을 켜 줘",
147
+ "calls": []
148
+ },
149
+ {
150
+ "id": "control-12",
151
+ "language": "en",
152
+ "query": "Turn on LED 9.",
153
+ "calls": []
154
+ },
155
+ {
156
+ "id": "control-13",
157
+ "language": "ko",
158
+ "query": "2번 LED 밝기를 300으로 바꿔 줘",
159
+ "calls": []
160
+ },
161
+ {
162
+ "id": "control-14",
163
+ "language": "en",
164
+ "query": "Play some music.",
165
+ "calls": []
166
+ },
167
+ {
168
+ "id": "control-15",
169
+ "language": "ko",
170
+ "query": "온도를 30도로 바꿔 줘",
171
+ "calls": []
172
+ },
173
+ {
174
+ "id": "control-16",
175
+ "language": "en",
176
+ "query": "Leave all LEDs unchanged.",
177
+ "calls": []
178
+ }
179
+ ]
@@ -0,0 +1,68 @@
1
+ [
2
+ {
3
+ "name": "turn_on",
4
+ "description": "Turn on one LED. Use the explicitly stated LED index 0 to 3.",
5
+ "parameters": {
6
+ "type": "object",
7
+ "properties": {
8
+ "index": {
9
+ "type": "integer",
10
+ "minimum": 0,
11
+ "maximum": 3
12
+ }
13
+ },
14
+ "required": [
15
+ "index"
16
+ ]
17
+ }
18
+ },
19
+ {
20
+ "name": "turn_off",
21
+ "description": "Turn off one LED. Use the explicitly stated LED index 0 to 3.",
22
+ "parameters": {
23
+ "type": "object",
24
+ "properties": {
25
+ "index": {
26
+ "type": "integer",
27
+ "minimum": 0,
28
+ "maximum": 3
29
+ }
30
+ },
31
+ "required": [
32
+ "index"
33
+ ]
34
+ }
35
+ },
36
+ {
37
+ "name": "set_brightness",
38
+ "description": "Set one LED brightness to the stated integer from 0 to 255.",
39
+ "parameters": {
40
+ "type": "object",
41
+ "properties": {
42
+ "index": {
43
+ "type": "integer",
44
+ "minimum": 0,
45
+ "maximum": 3
46
+ },
47
+ "value": {
48
+ "type": "integer",
49
+ "minimum": 0,
50
+ "maximum": 255
51
+ }
52
+ },
53
+ "required": [
54
+ "index",
55
+ "value"
56
+ ]
57
+ }
58
+ },
59
+ {
60
+ "name": "read_environment",
61
+ "description": "Read the current temperature and humidity. No changing sensor values.",
62
+ "parameters": {
63
+ "type": "object",
64
+ "properties": {},
65
+ "required": []
66
+ }
67
+ }
68
+ ]
@@ -0,0 +1,85 @@
1
+ """호출 정확도와 실제 LED 상태를 구분해서 확인한다."""
2
+
3
+ import json
4
+ import math
5
+ import statistics
6
+ import time
7
+
8
+ from . import validate_calls
9
+
10
+ INITIAL_LEDS = [0, 64, 128, 255]
11
+
12
+
13
+ def expected_leds(calls, initial=INITIAL_LEDS):
14
+ validate_calls(calls)
15
+ leds = list(initial)
16
+ for call in calls:
17
+ name, args = call["name"], call["arguments"]
18
+ if name != "read_environment":
19
+ leds[args["index"]] = (args["value"] if name == "set_brightness"
20
+ else 255 if name == "turn_on" else 0)
21
+ return leds
22
+
23
+
24
+ def evaluate(predict, board, cases):
25
+ """모든 실패를 분모에 남긴다. 예열 호출은 실행하지 않는다."""
26
+ if not cases:
27
+ raise ValueError("평가 문항이 없습니다.")
28
+ for case in cases:
29
+ validate_calls(case["calls"])
30
+ try:
31
+ predict("Turn on LED 0")
32
+ except Exception as exc:
33
+ print(f"예열 호출 실패: {exc}. 각 평가 문항은 계속 확인합니다.")
34
+ rows = []
35
+ for case in cases:
36
+ calls, error, valid, results = [], None, False, []
37
+ elapsed, actual, state_ok = None, None, False
38
+ try:
39
+ for index, value in enumerate(INITIAL_LEDS):
40
+ board.execute([{"name": "set_brightness", "arguments": {"index": index, "value": value}}])
41
+ before = board.state()
42
+ started = time.perf_counter()
43
+ try:
44
+ calls = predict(case["query"])
45
+ finally:
46
+ elapsed = time.perf_counter() - started
47
+ validate_calls(calls)
48
+ valid = True
49
+ results = board.execute(calls)
50
+ actual = board.state()["leds"]
51
+ state_ok = actual == expected_leds(case["calls"])
52
+ # 센서는 LED를 바꾸지 않는다. 반환값까지 대조한다.
53
+ for call, reply in zip(calls, results):
54
+ if call["name"] == "read_environment":
55
+ state_ok = state_ok and json.loads(reply.get("value", "null")) == [round(before["temperature"], 1), round(before["humidity"], 1)]
56
+ except Exception as exc:
57
+ error = str(exc)
58
+ names_ok = valid and [c["name"] for c in calls] == [c["name"] for c in case["calls"]]
59
+ exact = valid and calls == case["calls"]
60
+ success = bool(exact and state_ok and error is None)
61
+ row = {"id": case["id"], "language": case.get("language", "unknown"), "query": case["query"], "calls": calls,
62
+ "function_ok": names_ok, "exact": exact, "state_ok": state_ok,
63
+ "success": success, "latency": elapsed, "error": error,
64
+ "no_call": not case["calls"], "false_call": bool(calls) and not case["calls"]}
65
+ rows.append(row)
66
+ timing = f"{elapsed:.3f}s" if elapsed is not None else "추론 미실행"
67
+ print(f"{case['id']} {case['query']}\n 호출={calls}\n LED={actual} 완전일치={exact} 성공={success} {timing} 오류={error}")
68
+ n = len(rows)
69
+ latencies = sorted(r["latency"] for r in rows if r["latency"] is not None)
70
+ no_calls = [r for r in rows if r["no_call"]]
71
+ summary = {"count": n, "function_accuracy": sum(r["function_ok"] for r in rows) / n,
72
+ "call_accuracy": sum(r["exact"] for r in rows) / n,
73
+ "success_rate": sum(r["success"] for r in rows) / n,
74
+ "false_call_rate": sum(r["false_call"] for r in no_calls) / len(no_calls) if no_calls else None,
75
+ "latency_count": len(latencies),
76
+ "median_seconds": statistics.median(latencies) if latencies else None,
77
+ "p95_seconds": latencies[math.ceil(.95 * len(latencies)) - 1] if latencies else None}
78
+ summary["error_count"] = sum(r["error"] is not None for r in rows)
79
+ summary["by_language"] = {
80
+ language: sum(r["success"] for r in rows if r["language"] == language) /
81
+ sum(r["language"] == language for r in rows)
82
+ for language in sorted({r["language"] for r in rows})
83
+ }
84
+ print("평가 요약:", summary)
85
+ return rows, summary
@@ -0,0 +1,47 @@
1
+ """모델은 호출을 제안하며 실제 실행은 Board가 담당한다."""
2
+
3
+ import json
4
+ from copy import deepcopy
5
+ from threading import Lock
6
+
7
+ from . import DATA_DIR, http_json
8
+
9
+ TOOLS = json.loads((DATA_DIR / "tools.json").read_text(encoding="utf-8"))
10
+
11
+
12
+ def ollama_predict(question, model="qwen3.5:2b", url="http://127.0.0.1:11434/api/chat"):
13
+ body = http_json(url, {
14
+ "model": model,
15
+ "messages": [
16
+ {"role": "system", "content": "Use only the provided LED tools. LED indices are 0 to 3 and brightness is 0 to 255. Never guess missing indices or values. Unsupported, ambiguous, or invalid requests require no tool call. Never substitute a supported read for a requested write. Setting or changing temperature or humidity is unsupported and requires no tool call. Each request is independent."},
17
+ {"role": "user", "content": question},
18
+ ],
19
+ "tools": [{"type": "function", "function": tool} for tool in TOOLS],
20
+ "stream": False, "think": False,
21
+ "options": {"temperature": 0, "num_predict": 256},
22
+ }, timeout=120)
23
+ return [{"name": item["function"]["name"], "arguments": item["function"]["arguments"]}
24
+ for item in body["message"].get("tool_calls", [])]
25
+
26
+
27
+ def needle_predictor(weights=None, descriptions=None):
28
+ import cactus
29
+
30
+ tools = deepcopy(TOOLS)
31
+ for tool in tools:
32
+ if descriptions and tool["name"] in descriptions:
33
+ tool["description"] = descriptions[tool["name"]]
34
+ agent = cactus.Cactus(tools=tools, weights=str(weights) if weights else None, auto_date=False)
35
+ lock = Lock()
36
+
37
+ def predict(question):
38
+ with lock:
39
+ agent.reset() # 이전 질문의 문맥을 빼고 문항마다 독립적으로 비교한다.
40
+ result = agent.complete(question, max_new_tokens=256)
41
+ if not result.get("success"):
42
+ raise RuntimeError(result.get("error") or "Needle 응답 실패")
43
+ if result.get("validation", {}).get("ungrounded"):
44
+ return []
45
+ return result["function_calls"]
46
+
47
+ return predict
@@ -0,0 +1,84 @@
1
+ """cactus-compute 4.2.0의 로컬 학습 API를 호출하는 제공 코드."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+
7
+ from . import load_cases, validate_calls
8
+ from .models import TOOLS
9
+
10
+
11
+ def read_training(path):
12
+ rows = [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]
13
+ queries = set()
14
+ for row in rows:
15
+ if not isinstance(row.get("query"), str) or not row["query"].strip():
16
+ raise ValueError("학습 문장의 query가 비어 있습니다.")
17
+ if row["query"] in queries:
18
+ raise ValueError("같은 학습 질문이 중복되었습니다.")
19
+ queries.add(row["query"])
20
+ validate_calls(row["answers"])
21
+ if len(rows) < 10:
22
+ raise ValueError("검증 분리를 위해 학습 예제를 10개 이상 준비하세요.")
23
+ return rows
24
+
25
+
26
+ def train(source, output, epochs=4, batch_size=4, max_len=1024, learning_rate=1e-4):
27
+ rows = read_training(source)
28
+ overlap = {row["query"] for row in rows} & {case["query"] for case in load_cases()}
29
+ if overlap:
30
+ raise ValueError("학습과 평가에 같은 문장이 있습니다: " + str(sorted(overlap)))
31
+ output = Path(output)
32
+ output.mkdir(parents=True, exist_ok=True)
33
+ # 중단된 학습의 파일이 이전 결과와 섞여 사용되지 않도록 표시한다.
34
+ marker = output / ".training-in-progress"
35
+ marker.write_text("학습·내보내기 진행 중\n", encoding="utf-8")
36
+
37
+ import numpy as np
38
+ from cactus.model.finetune import finetune_local, render_example
39
+ from cactus.model.run import load_checkpoint
40
+ from cactus.model.tokenizer import get_tokenizer
41
+ from cactus.model.checkpoints import read_adapter, write_adapter
42
+ from cactus.model.build import build_main
43
+
44
+ checkpoint = output / "checkpoints" / "needle3.safetensors"
45
+ _, config = load_checkpoint(str(checkpoint))
46
+ tokenizer = get_tokenizer(config.vocab_size)
47
+ rows = [dict(row, tools=TOOLS) for row in rows]
48
+ longest = max(sum(len(tokenizer.encode(text)) for text in render_example(row)) + 2 for row in rows)
49
+ print(f"학습 데이터 {len(rows)}개, 가장 긴 문장 {longest}토큰, 제한 {max_len}토큰")
50
+ if longest > max_len:
51
+ raise ValueError("학습 예제가 잘릴 수 있습니다. MAX_LEN을 늘리거나 문장을 줄이세요.")
52
+ dataset = output / "training_input.jsonl"
53
+ dataset.write_text("\n".join(json.dumps(row, ensure_ascii=False) for row in rows) + "\n", encoding="utf-8")
54
+ adapter_path = output / "adapter.safetensors"
55
+ args = SimpleNamespace(checkpoint=str(checkpoint), jsonl_path=str(dataset),
56
+ epochs=epochs, batch_size=batch_size, max_len=max_len,
57
+ lr=learning_rate, lora_rank=16, lora_alpha=32,
58
+ val_split=0.125, seed=0, checkpoint_dir=str(output / "checkpoints"),
59
+ out=str(adapter_path), generate=0, score=False)
60
+ finetune_local(args)
61
+ # B=0인 어댑터는 가중치를 바꾸지 않는다. 기본·학습 모델 모두 같은 4비트로 내보낸다.
62
+ zero = read_adapter(str(adapter_path))
63
+ for values in zero["lora"].values():
64
+ values["B"] = np.zeros_like(values["B"])
65
+ zero_path = output / "baseline_adapter.safetensors"
66
+ write_adapter(str(zero_path), zero)
67
+ for adapter, filename in [(zero_path, "baseline.pending.cact"), (adapter_path, "tuned.pending.cact")]:
68
+ build_main(SimpleNamespace(checkpoint=str(checkpoint), lora=str(adapter),
69
+ out=str(output / filename), layers=20, platform=None, upload=False))
70
+ for name in ("baseline", "tuned"):
71
+ (output / f"{name}.pending.cact").replace(output / f"{name}.cact")
72
+ marker.unlink()
73
+ print("저장 완료: baseline.cact, tuned.cact. 다음에는 같은 평가 문항으로 비교하세요.")
74
+
75
+
76
+ def trained_path(directory, filename="tuned.cact"):
77
+ """이전 파일이 남았더라도 중단된 학습 결과는 읽지 않는다."""
78
+ directory = Path(directory)
79
+ if (directory / ".training-in-progress").exists():
80
+ raise RuntimeError("학습 또는 저장이 완료되지 않았습니다. 12주차 uv run ex02를 다시 실행하세요.")
81
+ for name in ("baseline.cact", "tuned.cact"):
82
+ if not (directory / name).is_file():
83
+ raise FileNotFoundError("먼저 12주차 uv run ex02로 모델 두 개를 저장하세요.")
84
+ return directory / filename