dsh-qqbot-muu 0.1.15 → 0.1.21

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 (171) hide show
  1. package/CHANGELOG.md +168 -85
  2. package/client/qqbot-settings.js +13401 -12024
  3. package/config/modules.json +212 -0
  4. package/dist/channel-tools.js +21 -10
  5. package/dist/config.d.ts +14 -0
  6. package/dist/config.js +573 -449
  7. package/dist/features/contextless-store.js +247 -247
  8. package/dist/features/contextless-trim.js +455 -34
  9. package/dist/features/four-source.js +338 -336
  10. package/dist/features/group-join-request.js +289 -287
  11. package/dist/features/local-models.js +1494 -0
  12. package/dist/features/rotate-summarizer.js +438 -0
  13. package/dist/features/scenario-detect.js +321 -0
  14. package/dist/features/scheduler.js +8 -1
  15. package/dist/features/session-rotate.js +499 -0
  16. package/dist/features/session-title.js +199 -0
  17. package/dist/features/style-layer.js +501 -0
  18. package/dist/features/thinking-log.js +71 -69
  19. package/dist/gateway/bootstrap.js +1704 -1388
  20. package/dist/gateway/data-root.js +77 -3
  21. package/dist/gateway/middleware-setup.js +6 -3
  22. package/dist/index.js +4 -2
  23. package/dist/model/settings-reader.js +193 -102
  24. package/dist/session/session-manager.js +1730 -1587
  25. package/dist/shared/paths.js +128 -0
  26. package/dist/shared/settings-io.js +79 -0
  27. package/dist/transport/inbound.js +20 -1
  28. package/dist/transport/outbound.js +56 -4
  29. package/docs/RELEASE_CHECKLIST.md +24 -2
  30. package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
  31. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  32. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
  33. package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
  34. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  35. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  36. package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
  37. package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
  38. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
  39. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  40. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  41. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  42. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  43. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  44. package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
  45. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  46. package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
  47. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  48. package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
  49. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  50. package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
  51. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  52. package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
  53. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  54. package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
  55. package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
  56. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  57. package/package.json +119 -111
  58. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  59. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  60. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  61. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  62. package/scripts/_add_maintenance_cfg.py +20 -0
  63. package/scripts/_bench_keeplease.sh +10 -0
  64. package/scripts/_dbg_purge.py +15 -0
  65. package/scripts/_elev.sh +6 -0
  66. package/scripts/_fix_all_admin.cmd +16 -0
  67. package/scripts/_livecheck-image.mjs +33 -0
  68. package/scripts/_livecheck-llm.mjs +34 -0
  69. package/scripts/_livecheck-tts.mjs +37 -0
  70. package/scripts/_patch_curve.py +88 -0
  71. package/scripts/_patch_fan_thermal.py +24 -0
  72. package/scripts/_tag_tmp.py +13 -0
  73. package/scripts/adb-broker-client.mjs +87 -0
  74. package/scripts/adb-broker.mjs +205 -0
  75. package/scripts/ai-mode.cmd +6 -0
  76. package/scripts/ai-mode.py +387 -0
  77. package/scripts/ai-toolkit.py +607 -0
  78. package/scripts/apply-fan-gpu45.py +51 -0
  79. package/scripts/bench-fans.py +515 -0
  80. package/scripts/bench-load-direct.py +63 -0
  81. package/scripts/boot-tasks-hidden.vbs +20 -0
  82. package/scripts/boot-tasks.cmd +277 -0
  83. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  84. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  85. package/scripts/chat-archive/build-sft-v4.py +566 -0
  86. package/scripts/chat-archive/build-sft.py +390 -0
  87. package/scripts/chat-archive/eval-sft.py +155 -0
  88. package/scripts/chat-archive/extract-memory.py +143 -0
  89. package/scripts/chat-archive/inventory.py +182 -0
  90. package/scripts/chat-archive/merge-sft.py +114 -0
  91. package/scripts/chat-archive/qce-pull.py +217 -0
  92. package/scripts/chat-archive/qqheader.py +110 -0
  93. package/scripts/chat-archive/qqkey2.py +113 -0
  94. package/scripts/chat-archive/qqprobe.py +153 -0
  95. package/scripts/chat-archive/screen-collect.py +163 -0
  96. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  97. package/scripts/comfy_gen.py +209 -0
  98. package/scripts/compose-video.py +168 -0
  99. package/scripts/dl_models.py +45 -0
  100. package/scripts/draw-now.cmd +18 -0
  101. package/scripts/dsh-instance-guard.mjs +20 -2
  102. package/scripts/elev-extra.cmd +25 -0
  103. package/scripts/episode.py +529 -0
  104. package/scripts/fan-curve.py +218 -0
  105. package/scripts/fan-guard.cmd +8 -0
  106. package/scripts/fan-mode.py +380 -0
  107. package/scripts/fan_manual_safe.py +33 -0
  108. package/scripts/fan_restore_manual.py +46 -0
  109. package/scripts/fc_curves.py +359 -0
  110. package/scripts/fix-fan-and-timers.cmd +39 -0
  111. package/scripts/fix_admin_all.py +94 -0
  112. package/scripts/flows.mjs +224 -0
  113. package/scripts/gateway.cmd +126 -0
  114. package/scripts/gen-image.py +420 -0
  115. package/scripts/gen-video.py +186 -0
  116. package/scripts/git-askpass.cmd +2 -2
  117. package/scripts/gpu-mode.py +195 -0
  118. package/scripts/hw-profile.py +175 -0
  119. package/scripts/install-schedule.cmd +37 -0
  120. package/scripts/install-watch.cmd +29 -0
  121. package/scripts/matte-cutout.py +106 -0
  122. package/scripts/media-enhance.py +402 -0
  123. package/scripts/memory-audit.py +581 -0
  124. package/scripts/migrate-scope.mjs +140 -139
  125. package/scripts/model-registry.py +519 -0
  126. package/scripts/openid-audit.mjs +219 -0
  127. package/scripts/pull-gguf.py +127 -0
  128. package/scripts/purge-standby.py +151 -0
  129. package/scripts/qq-connect-login.py +133 -0
  130. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  131. package/scripts/qq-ip-sync.py +300 -0
  132. package/scripts/qq-login-once.cmd +20 -0
  133. package/scripts/qq-login-qr.py +72 -0
  134. package/scripts/qq-whitelist-fix.cmd +27 -0
  135. package/scripts/qq-whitelist-login.cmd +26 -0
  136. package/scripts/qq-whitelist.cmd +12 -0
  137. package/scripts/qq-whitelist.py +1452 -0
  138. package/scripts/quality-compare.py +134 -0
  139. package/scripts/release-all.mjs +636 -430
  140. package/scripts/release-check.mjs +244 -226
  141. package/scripts/resume-coder.cmd +38 -0
  142. package/scripts/secure-room/index.html +334 -0
  143. package/scripts/secure-room/server.py +582 -0
  144. package/scripts/security-check.mjs +164 -0
  145. package/scripts/selftest-local-llm.mjs +20 -0
  146. package/scripts/selftest-local-models.mjs +754 -0
  147. package/scripts/selftest-rotate-style.mjs +308 -0
  148. package/scripts/shutdown-s5-optional.cmd +21 -0
  149. package/scripts/sleep-2325.cmd +75 -0
  150. package/scripts/start-comfyui.cmd +5 -0
  151. package/scripts/start-strata.cmd +17 -0
  152. package/scripts/start-strata.vbs +11 -0
  153. package/scripts/start-watch-hidden.vbs +3 -0
  154. package/scripts/stickers/auto-tag.mjs +161 -0
  155. package/scripts/storage.mjs +236 -0
  156. package/scripts/sync-plugin-copies.mjs +98 -23
  157. package/scripts/tests/test-qq-whitelist.py +192 -0
  158. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  159. package/scripts/train/gguf-quantize.py +92 -0
  160. package/scripts/train/gguf-to-hf.py +112 -0
  161. package/scripts/train/merge-lora.py +51 -0
  162. package/scripts/train/probe-mirrors.sh +12 -0
  163. package/scripts/train/probe-mirrors2.sh +20 -0
  164. package/scripts/train/setup-wsl.sh +23 -0
  165. package/scripts/train/setup-wsl2.sh +25 -0
  166. package/scripts/train/setup-wsl3.sh +22 -0
  167. package/scripts/train/setup-wsl4.sh +22 -0
  168. package/scripts/train/train-lora.py +319 -0
  169. package/scripts/vram-free.py +104 -0
  170. package/scripts/wechat-full-pull.mjs +1 -1
  171. package/settings-host.js +1047 -12
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ train-lora.py — 给「小家/小蓝」做 QLoRA 风格微调(8B,单卡 22GB)
5
+
6
+ 为什么是自己写而不是拉一套 LLaMA-Factory:
7
+ 数据集只有 3k 条、目标是"说话更像人"而不是灌知识,参数越少越不容易把
8
+ 原本的人味训没。这里把关键项都摆在命令行上,跑之前能看懂每一格。
9
+
10
+ 数据:archive/sft4/dataset/{train,val}.jsonl,每行 {"messages":[system,user,assistant],...}
11
+ 做法:
12
+ · 4bit 量化加载基座(nf4 + double quant),LoRA 只训注意力和 MLP 的投影
13
+ · 用基座自己的 chat template 拼文本(enable_thinking=False,否则 Qwen3 会
14
+ 学到"每条都先想一大段",线上就变成只思考不说话)
15
+ · 超长样本从左边截:保住末尾的 assistant 回复(那才是要学的东西)
16
+
17
+ 用法:
18
+ python scripts/train/train-lora.py --smoke # 只跑 6 步,验证链路(约 2 分钟)
19
+ python scripts/train/train-lora.py # 正式训练(3 epoch)
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import inspect
25
+ import json
26
+ import os
27
+ import subprocess
28
+ import sys
29
+ import time
30
+
31
+ import torch
32
+ from transformers import TrainerCallback
33
+
34
+
35
+ def _gpu_line() -> str:
36
+ """nvidia-smi 读温度/占用;WSL 里同样可用。失败就返回空串(不影响训练)。"""
37
+ try:
38
+ out = subprocess.check_output(
39
+ ['nvidia-smi',
40
+ '--query-gpu=temperature.gpu,utilization.gpu,memory.used,memory.total',
41
+ '--format=csv,noheader,nounits'],
42
+ timeout=2, stderr=subprocess.DEVNULL).decode('utf-8', 'ignore').strip().splitlines()[0]
43
+ t, u, mu, mt = [x.strip() for x in out.split(',')]
44
+ return f'GPU {t}°C {u}% {float(mu) / 1024:.1f}/{float(mt) / 1024:.1f}GB'
45
+ except Exception:
46
+ return ''
47
+
48
+
49
+ class ProgressPrinter(TrainerCallback):
50
+ """每一步都打进度条:百分比 + 已用/剩余 + loss + GPU 温度。
51
+
52
+ 为什么不用 tqdm:训练常被重定向到日志文件(非 TTY),tqdm 会整条静默,
53
+ 这正是"看不到进度"的原因。这里直接 print + flush,同时写一份到 out/train-progress.log。
54
+ """
55
+
56
+ def __init__(self, every: int = 1, log_path: str = ''):
57
+ self.every = max(1, int(every))
58
+ self.log_path = log_path
59
+ self.t0 = 0.0
60
+ self.total = 0
61
+ self._gpu = ''
62
+ self._gpu_at = 0.0
63
+
64
+ def _emit(self, line: str) -> None:
65
+ print(line, flush=True)
66
+ if not self.log_path:
67
+ return
68
+ try:
69
+ with open(self.log_path, 'a', encoding='utf-8') as f:
70
+ f.write(line + '\n')
71
+ except Exception:
72
+ pass
73
+
74
+ def on_train_begin(self, args, state, control, **kwargs):
75
+ self.t0 = time.time()
76
+ self.total = int(state.max_steps or args.max_steps or 0)
77
+ self._emit(f'[训练开始] 总步数 {self.total} | batch {args.per_device_train_batch_size}'
78
+ f' × 累积 {args.gradient_accumulation_steps} | lr {args.learning_rate}')
79
+
80
+ def on_step_end(self, args, state, control, **kwargs):
81
+ step = int(state.global_step or 0)
82
+ if step % self.every or not self.total:
83
+ return
84
+ now = time.time()
85
+ el = now - self.t0
86
+ eta = (el / step) * (self.total - step) if step else 0.0
87
+ pct = 100.0 * step / self.total
88
+ width = 24
89
+ bar = '█' * int(width * step / self.total) + '░' * (width - int(width * step / self.total))
90
+ loss = '—'
91
+ for rec in reversed(state.log_history):
92
+ if 'loss' in rec:
93
+ loss = f"{rec['loss']:.3f}"
94
+ break
95
+ if now - self._gpu_at > 10:
96
+ self._gpu = _gpu_line()
97
+ self._gpu_at = now
98
+ gpu = f' | {self._gpu}' if self._gpu else ''
99
+ self._emit(f'[{bar}] {pct:5.1f}% step {step}/{self.total} | '
100
+ f'已用 {el / 60:5.1f}min 剩 {eta / 60:5.1f}min | loss {loss}{gpu}')
101
+
102
+ def on_train_end(self, args, state, control, **kwargs):
103
+ el = time.time() - self.t0
104
+ self._emit(f'[训练结束] {int(state.global_step or 0)} 步,用时 {el / 60:.1f} 分钟')
105
+
106
+
107
+ def build_rows(path: str, tok, max_len: int) -> list[dict]:
108
+ """把 messages 变成「只对 assistant 算 loss」的 token 序列。
109
+
110
+ 为什么必须掩码(2026-12-04 查出的最大问题):
111
+ 旧实现把整段 chat template 当纯文本交给 SFTTrainer,system 和 user 的 token
112
+ 也参与 loss —— 模型被训练去"生成用户的提问"和"背系统提示"。
113
+ 数据再干净也架不住这个,表现就是答非所问、爱复读、爱念设定。
114
+ 现在 prompt 段 completion_mask=0(loss 忽略),只有 assistant 回复 + 结束符算 loss。
115
+ """
116
+ rows = []
117
+ bad = 0
118
+ eot = None
119
+ try:
120
+ eot = tok.convert_tokens_to_ids('<|im_end|>')
121
+ if eot is None or eot == tok.unk_token_id:
122
+ eot = None
123
+ except Exception:
124
+ eot = None
125
+ with open(path, encoding='utf-8') as f:
126
+ for line in f:
127
+ line = line.strip()
128
+ if not line:
129
+ continue
130
+ try:
131
+ msgs = json.loads(line)['messages']
132
+ assert msgs[-1]['role'] == 'assistant'
133
+ except Exception:
134
+ bad += 1
135
+ continue
136
+ prompt, answer = msgs[:-1], str(msgs[-1]['content'])
137
+ # enable_thinking=False:Qwen3 模板里不加空的 thinking 段,
138
+ # 这样模型学到的就是"直接说话"(线上要的正是这个)
139
+ try:
140
+ prompt_text = tok.apply_chat_template(
141
+ prompt, tokenize=False, add_generation_prompt=True, enable_thinking=False)
142
+ except TypeError:
143
+ prompt_text = tok.apply_chat_template(
144
+ prompt, tokenize=False, add_generation_prompt=True)
145
+ p_ids = tok(prompt_text, add_special_tokens=False)['input_ids']
146
+ a_ids = tok(answer, add_special_tokens=False)['input_ids']
147
+ if eot is not None:
148
+ a_ids = a_ids + [eot]
149
+ # 超长从左边砍 prompt,保住整段 assistant(那才是要学的东西)
150
+ budget = max_len - len(a_ids)
151
+ if budget < 8:
152
+ a_ids = a_ids[:max(1, max_len - 8)] + ([eot] if eot is not None else [])
153
+ budget = max(1, max_len - len(a_ids))
154
+ if len(p_ids) > budget:
155
+ p_ids = p_ids[-budget:]
156
+ ids = list(p_ids) + list(a_ids)
157
+ rows.append({
158
+ 'input_ids': ids,
159
+ 'completion_mask': [0] * len(p_ids) + [1] * len(a_ids),
160
+ })
161
+ if bad:
162
+ print(f' [warn] 跳过坏行 {bad} 条')
163
+ return rows
164
+
165
+
166
+ def main():
167
+ ap = argparse.ArgumentParser()
168
+ # 默认路径按 WSL(Ubuntu) 训练环境写:权重在 /mnt/e,数据在 /mnt/f,产物落 ext4(写快)
169
+ ap.add_argument('--base', default='/mnt/e/AI/models/Qwen3-8B-abliterated-hf')
170
+ ap.add_argument('--train', default='/mnt/f/qqbot/archive/sft4/dataset/train.jsonl')
171
+ ap.add_argument('--val', default='/mnt/f/qqbot/archive/sft4/dataset/val.jsonl')
172
+ ap.add_argument('--out', default='/opt/train/out5')
173
+ ap.add_argument('--epochs', type=float, default=2)
174
+ ap.add_argument('--max-len', type=int, default=1024)
175
+ ap.add_argument('--batch', type=int, default=4)
176
+ ap.add_argument('--accum', type=int, default=4)
177
+ ap.add_argument('--lr', type=float, default=2e-4)
178
+ ap.add_argument('--progress-every', type=int, default=1, help='每多少步打一行进度(默认每步)')
179
+ ap.add_argument('--bf16', action='store_true', help='Ampere+ 才开;2080Ti(Turing) 必须用 fp16')
180
+ ap.add_argument('--smoke', action='store_true', help='只跑几步验证链路')
181
+ a = ap.parse_args()
182
+
183
+ # 2080 Ti 是 Turing(SM7.5),没有 bf16 张量核心:用 bf16 会静默回落 fp32,
184
+ # 实测每步 89 秒(本该 2~3 秒)。所以默认 fp16,并把 TF32 打开。
185
+ torch.backends.cuda.matmul.allow_tf32 = True
186
+ torch.backends.cudnn.allow_tf32 = True
187
+ compute_dtype = torch.bfloat16 if a.bf16 else torch.float16
188
+
189
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
190
+ from peft import LoraConfig
191
+ from trl import SFTTrainer, SFTConfig
192
+ from datasets import Dataset
193
+
194
+ print(f'[1/5] 加载 tokenizer:{a.base}')
195
+ tok = AutoTokenizer.from_pretrained(a.base, trust_remote_code=True)
196
+
197
+ print(f'[2/5] 读数据:{a.train}')
198
+ t0 = time.time()
199
+ train_rows = build_rows(a.train, tok, a.max_len)
200
+ val_rows = build_rows(a.val, tok, a.max_len)
201
+ print(f' train={len(train_rows)} val={len(val_rows)}({time.time() - t0:.1f}s)')
202
+ # 掩码体检:assistant 之外的 token 应该一条都不参与 loss
203
+ if train_rows:
204
+ ids_n = [len(r['input_ids']) for r in train_rows]
205
+ ans_n = [sum(r['completion_mask']) for r in train_rows]
206
+ ids_n.sort()
207
+ print(f' 序列长度 p50={ids_n[len(ids_n) // 2]} p95={ids_n[int(len(ids_n) * 0.95)]} '
208
+ f'max={ids_n[-1]} | 只对 assistant 算 loss:'
209
+ f'答案占 {sum(ans_n) / max(1, sum(ids_n)) * 100:.1f}% 的 token')
210
+
211
+ print('[3/5] 4bit 加载基座(约 5GB 显存)')
212
+ bnb = BitsAndBytesConfig(
213
+ load_in_4bit=True,
214
+ bnb_4bit_quant_type='nf4',
215
+ bnb_4bit_use_double_quant=True,
216
+ bnb_4bit_compute_dtype=compute_dtype,
217
+ )
218
+ model = AutoModelForCausalLM.from_pretrained(
219
+ a.base, quantization_config=bnb, device_map={'': 0}, trust_remote_code=True,
220
+ attn_implementation='sdpa',
221
+ # 必须显式指定:Qwen3 的 config 里 torch_dtype=bfloat16,不指定就会把
222
+ # 未量化的层(LoRA/embed/norm)建成 bf16 → Turing 卡上 fp16 scaler 直接报
223
+ # "_amp_foreach_non_finite_check_and_unscale_cuda not implemented for BFloat16"
224
+ torch_dtype=compute_dtype,
225
+ )
226
+ model.config.use_cache = False
227
+
228
+ lora = LoraConfig(
229
+ r=16, lora_alpha=32, lora_dropout=0.05, bias='none', task_type='CAUSAL_LM',
230
+ target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj'],
231
+ )
232
+
233
+ print('[4/5] 组装训练器')
234
+ kwargs = dict(
235
+ output_dir=a.out,
236
+ num_train_epochs=a.epochs,
237
+ per_device_train_batch_size=a.batch,
238
+ per_device_eval_batch_size=1,
239
+ gradient_accumulation_steps=a.accum,
240
+ learning_rate=a.lr,
241
+ lr_scheduler_type='cosine',
242
+ warmup_ratio=0.03,
243
+ logging_steps=1, # 每步都有 loss 可看(进度条要用;开销可忽略)
244
+ save_strategy='no' if a.smoke else 'epoch',
245
+ eval_strategy='no' if a.smoke else 'epoch',
246
+ # 每个 epoch 都验一次,按 eval_loss 选最好的那份保存;连涨两轮就停(小数据必须防过拟合)
247
+ load_best_model_at_end=not a.smoke,
248
+ metric_for_best_model='eval_loss',
249
+ greater_is_better=False,
250
+ save_total_limit=2,
251
+ # 进度由 ProgressPrinter 打(tqdm 在非 TTY/重定向日志时会整条消失)
252
+ disable_tqdm=True,
253
+ bf16=a.bf16,
254
+ # 不开 fp16 AMP:GradScaler 会对全模型参数做 bf16 有限性检查,
255
+ # 只要有一个 bf16 参数就抛 NotImplementedError(Turing 卡上必现)。
256
+ # LoRA 参数本身是 fp32,关掉 scaler 后梯度不会下溢,速度几乎无差。
257
+ fp16=False,
258
+ gradient_checkpointing=True,
259
+ gradient_checkpointing_kwargs={'use_reentrant': False},
260
+ report_to=[],
261
+ packing=False,
262
+ optim='paged_adamw_8bit',
263
+ seed=42,
264
+ )
265
+ sig = inspect.signature(SFTConfig.__init__).parameters
266
+ kwargs['max_length' if 'max_length' in sig else 'max_seq_length'] = a.max_len
267
+ # 预分词 + completion_mask:数据已经是 input_ids/completion_mask 两列,
268
+ # 不能再让 SFTTrainer 去 dataset_text_field 里找纯文本(那样掩码就丢了)。
269
+ if 'completion_only_loss' in sig:
270
+ kwargs['completion_only_loss'] = True
271
+ if 'skip_prepare_dataset' in sig:
272
+ kwargs['skip_prepare_dataset'] = True
273
+ if a.smoke:
274
+ kwargs['max_steps'] = 6
275
+ kwargs.pop('num_train_epochs', None)
276
+ cfg = SFTConfig(**kwargs)
277
+ trainer_kw = dict(model=model, args=cfg, train_dataset=Dataset.from_list(train_rows),
278
+ eval_dataset=Dataset.from_list(val_rows) if val_rows else None,
279
+ peft_config=lora)
280
+ tsig = inspect.signature(SFTTrainer.__init__).parameters
281
+ if 'processing_class' in tsig:
282
+ trainer_kw['processing_class'] = tok
283
+ else:
284
+ trainer_kw['tokenizer'] = tok
285
+ trainer = SFTTrainer(**trainer_kw)
286
+ try:
287
+ if not a.smoke:
288
+ from transformers import EarlyStoppingCallback
289
+ # 小数据(1.6k 条)连涨两轮就停:再训只会背样本,人味反而掉
290
+ trainer.add_callback(EarlyStoppingCallback(early_stopping_patience=1))
291
+ if hasattr(trainer.model, 'print_trainable_parameters'):
292
+ trainer.model.print_trainable_parameters()
293
+ except Exception as e:
294
+ print(f' [warn] 训练器回调挂载失败(训练继续):{e}')
295
+
296
+ # 开训前先把"要跑多少步"说清楚,别让人盯着黑屏猜
297
+ step_bs = max(1, a.batch * a.accum)
298
+ per_epoch = (len(train_rows) + step_bs - 1) // step_bs
299
+ total_steps = 6 if a.smoke else int(per_epoch * a.epochs)
300
+ print(f' 训练集 {len(train_rows)} 条 / 验证集 {len(val_rows)} 条')
301
+ print(f' 每 epoch {per_epoch} 步,计划共 {total_steps} 步;之后每 {a.progress_every} 步打印一行进度')
302
+ try:
303
+ os.makedirs(a.out, exist_ok=True)
304
+ trainer.add_callback(ProgressPrinter(a.progress_every, os.path.join(a.out, 'train-progress.log')))
305
+ except Exception as e:
306
+ print(f' [warn] 进度回调挂载失败(训练继续,只是少进度条):{e}')
307
+
308
+ print('[5/5] 开训')
309
+ t1 = time.time()
310
+ trainer.train()
311
+ mins = (time.time() - t1) / 60
312
+ print(f'训练完成,用时 {mins:.1f} 分钟')
313
+ trainer.save_model(a.out)
314
+ tok.save_pretrained(a.out)
315
+ print('LoRA 已保存:', a.out)
316
+
317
+
318
+ if __name__ == '__main__':
319
+ main()
@@ -0,0 +1,104 @@
1
+ # -*- coding: utf-8 -*-
2
+ """vram-free.py —— 显存仲裁:把别家占着显存的模型先请出去,再让下一个上去。
3
+
4
+ 为什么需要:22GB 只有一张 2080 Ti。
5
+ · ComfyUI(8191) 出完图会把 FLUX/VAE 留在显存(~11GB)
6
+ · Ollama(11434) 默认 keep_alive=5m,qwen2.5:7b 占 ~5GB
7
+ · Strata(8080) 起 35B 要 ~12GB
8
+ 三者硬叠必然 OOM。谁要上场,先把自己以外的都赶下去。
9
+
10
+ 用法:
11
+ python scripts/vram-free.py --all # ComfyUI + Ollama 都清
12
+ python scripts/vram-free.py --comfy # 只清 ComfyUI
13
+ python scripts/vram-free.py --ollama # 只卸 Ollama 模型
14
+ python scripts/vram-free.py --all --json # 给脚本/面板读
15
+ 不用管理员权限;没有任何弹窗(子进程一律 CREATE_NO_WINDOW)。
16
+ """
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+ import urllib.request
22
+
23
+ COMFY = os.environ.get("COMFY_URL", "http://127.0.0.1:8191")
24
+ OLLAMA = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
25
+ CREATE_NO_WINDOW = 0x08000000
26
+
27
+
28
+ def post(url, payload, timeout=8):
29
+ req = urllib.request.Request(
30
+ url, data=json.dumps(payload).encode("utf-8"),
31
+ headers={"Content-Type": "application/json"}, method="POST")
32
+ with urllib.request.urlopen(req, timeout=timeout) as r:
33
+ return r.status
34
+
35
+
36
+ def get(url, timeout=6):
37
+ with urllib.request.urlopen(url, timeout=timeout) as r:
38
+ return json.loads(r.read().decode("utf-8"))
39
+
40
+
41
+ def vram():
42
+ try:
43
+ out = subprocess.run(
44
+ ["nvidia-smi", "--query-gpu=memory.used,memory.total", "--format=csv,noheader,nounits"],
45
+ capture_output=True, text=True, timeout=15, creationflags=CREATE_NO_WINDOW)
46
+ used, total = [int(x) for x in out.stdout.strip().split(",")]
47
+ return {"used_mb": used, "total_mb": total}
48
+ except Exception:
49
+ return None
50
+
51
+
52
+ def free_comfy():
53
+ """ComfyUI: 卸载模型 + 释放缓存。"""
54
+ try:
55
+ post(COMFY + "/free", {"unload_models": True, "free_memory": True})
56
+ return True
57
+ except Exception as e:
58
+ return "ERR: %s" % e
59
+
60
+
61
+ def free_ollama():
62
+ """Ollama: 对每个已加载模型发 keep_alive=0。"""
63
+ try:
64
+ ps = get(OLLAMA + "/api/ps")
65
+ except Exception as e:
66
+ return "ERR: %s" % e
67
+ names = [m.get("name") or m.get("model") for m in (ps.get("models") or [])]
68
+ for n in names:
69
+ if not n:
70
+ continue
71
+ try:
72
+ post(OLLAMA + "/api/generate", {"model": n, "keep_alive": 0}, timeout=10)
73
+ except Exception:
74
+ pass
75
+ return names
76
+
77
+
78
+ def main():
79
+ want_comfy = "--comfy" in sys.argv or "--all" in sys.argv or len(sys.argv) == 1
80
+ want_ollama = "--ollama" in sys.argv or "--all" in sys.argv or len(sys.argv) == 1
81
+ as_json = "--json" in sys.argv
82
+
83
+ before = vram()
84
+ res = {}
85
+ if want_comfy:
86
+ res["comfyui"] = free_comfy()
87
+ if want_ollama:
88
+ res["ollama"] = free_ollama()
89
+ after = vram()
90
+ res["vram_before"] = before
91
+ res["vram_after"] = after
92
+ if as_json:
93
+ print(json.dumps(res, ensure_ascii=False))
94
+ else:
95
+ print("comfyui: %s" % res.get("comfyui", "skipped"))
96
+ print("ollama : %s" % res.get("ollama", "skipped"))
97
+ if before and after:
98
+ print("vram : %d MB -> %d MB (free %d MB)" %
99
+ (before["used_mb"], after["used_mb"], before["used_mb"] - after["used_mb"]))
100
+ return 0
101
+
102
+
103
+ if __name__ == "__main__":
104
+ sys.exit(main())
@@ -34,7 +34,7 @@ const __repoRoot = (() => {
34
34
  * 平板微信全量快照 → 私有归档库
35
35
  *
36
36
  * 现实(2026-11-16 实测):
37
- * - 平板上的微信是「小蓝自己的号」(wxid_x9oo19tcn4gm12 / MuUAstra),2026-11-05 才建。
37
+ * - 平板上的微信是「小蓝自己的号」(wxid_xxx / MuUAstra),2026-11-05 才建。
38
38
  * - WCX 只给 /api/conversations/<id>/history(page-index 分页,最新在前),
39
39
  * 单条只有 {sender, content, type}:没有时间戳、没有 msgId、没有媒体地址。
40
40
  * - 能翻到的总量就是这台设备上的全部:家长 146 / 家人 31 / 家庭群 75 / filehelper 4。