dsh-qqbot-muu 0.1.20 → 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.
- package/CHANGELOG.md +168 -154
- package/client/qqbot-settings.js +13401 -13380
- package/dist/config.js +573 -581
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -1467
- package/dist/features/style-layer.js +501 -498
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1652
- package/dist/model/settings-reader.js +193 -102
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -83
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -118
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/ai-toolkit.py +607 -478
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -263
- package/scripts/gen-image.py +420 -413
- package/scripts/gen-video.py +186 -178
- package/scripts/hw-profile.py +175 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-whitelist.py +71 -0
- package/scripts/release-all.mjs +636 -509
- package/scripts/release-check.mjs +244 -226
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
- package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
- package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
- package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
- package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
- package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
- package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
- package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
- package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* auto-tag.mjs — 表情包批量打标签(本地视觉模型,零云 token)
|
|
4
|
+
*
|
|
5
|
+
* 背景(2026-12-03 主人指出的短板):表情库有 160+ 张,但一部分只有自由标签、
|
|
6
|
+
* 一部分连描述都没有,检索时只能靠字面撞词 ——「发一个无语的」经常挑不出来。
|
|
7
|
+
*
|
|
8
|
+
* 做法:
|
|
9
|
+
* 1. 只挑「没打过五面标签 / 缺描述」的条目,不重刷已经标好的;
|
|
10
|
+
* 2. 本地 ollama 视觉模型(默认 qwen3-vl:8b)看图,吐严格 JSON:
|
|
11
|
+
* desc / emotion / scene / action / intensity;
|
|
12
|
+
* 3. 过 sticker-schema 的 applyTagSchema 收口到词表,写回 index.json。
|
|
13
|
+
*
|
|
14
|
+
* 安全:每张写完立刻落盘(中途退出不丢进度);任何一张失败都只跳过并记日志。
|
|
15
|
+
*
|
|
16
|
+
* 用法:
|
|
17
|
+
* node scripts/stickers/auto-tag.mjs --limit 40 # 先跑 40 张看看效果
|
|
18
|
+
* node scripts/stickers/auto-tag.mjs # 把剩下的都补完
|
|
19
|
+
* node scripts/stickers/auto-tag.mjs --dry # 只列出待补的,不调模型
|
|
20
|
+
*/
|
|
21
|
+
import { readFileSync, writeFileSync, existsSync, renameSync } from 'node:fs'
|
|
22
|
+
import { join, dirname } from 'node:path'
|
|
23
|
+
import { fileURLToPath } from 'node:url'
|
|
24
|
+
import {
|
|
25
|
+
applyTagSchema, auditItems, facetsOf, EMOTIONS, SCENES, ACTIONS, SCHEMA_VERSION,
|
|
26
|
+
} from '../../dshqqbot/.qqbot-extensions/lib/sticker-schema.mjs'
|
|
27
|
+
|
|
28
|
+
const HERE = dirname(fileURLToPath(import.meta.url))
|
|
29
|
+
const REPO = join(HERE, '..', '..')
|
|
30
|
+
const ROOT = process.env.QQBOT_MEMORY_DATA_ROOT || join(REPO, 'dshqqbot')
|
|
31
|
+
const INDEX = join(ROOT, '表情包', 'index.json')
|
|
32
|
+
const OLLAMA = (() => {
|
|
33
|
+
const raw = String(process.env.OLLAMA_HOST || 'http://127.0.0.1:11434').trim()
|
|
34
|
+
return /^https?:\/\//i.test(raw) ? raw.replace(/\/+$/, '') : 'http://' + raw.replace(/\/+$/, '')
|
|
35
|
+
})()
|
|
36
|
+
|
|
37
|
+
function argOf(name, dflt) {
|
|
38
|
+
const i = process.argv.indexOf('--' + name)
|
|
39
|
+
if (i < 0) return dflt
|
|
40
|
+
const v = process.argv[i + 1]
|
|
41
|
+
return v && !v.startsWith('--') ? v : true
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const LIMIT = Number(argOf('limit', 0)) || 0
|
|
45
|
+
const MODEL = String(argOf('model', 'qwen3-vl:8b'))
|
|
46
|
+
const DRY = Boolean(argOf('dry', false))
|
|
47
|
+
|
|
48
|
+
/** 只有"没标签 / 缺描述 / 还不是新版 schema"的才补,标好的不重刷 */
|
|
49
|
+
function needsWork(it) {
|
|
50
|
+
const f = facetsOf(it)
|
|
51
|
+
return it.tagSchema !== SCHEMA_VERSION || !f.emotion.length || it.needsDescribe === true || !(it.desc || it.descZh)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function fileOf(it) {
|
|
55
|
+
const base = join(ROOT, '表情包', 'lib', String(it.layer || 'candidate'))
|
|
56
|
+
for (const ext of [it.ext, 'jpg', 'png', 'gif', 'webp']) {
|
|
57
|
+
if (!ext) continue
|
|
58
|
+
const p = join(base, `${it.id}.${ext}`)
|
|
59
|
+
if (existsSync(p)) return p
|
|
60
|
+
}
|
|
61
|
+
return ''
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const PROMPT = `/no_think 你是表情包整理员。看这张图,只输出一个 JSON,不要任何解释:
|
|
65
|
+
{"desc":"一句话画面描述(30字内)","emotion":["3个以内"],"scene":["2个以内"],"action":["1个以内"],"intensity":"low|mid|high"}
|
|
66
|
+
emotion 只能从这个词表里选:${EMOTIONS.join('、')}
|
|
67
|
+
scene 只能从这个词表里选:${SCENES.join('、')}
|
|
68
|
+
action 只能从这个词表里选:${ACTIONS.join('、')}
|
|
69
|
+
如果图上没有人物动作,action 给空数组。`
|
|
70
|
+
|
|
71
|
+
function parseJson(s) {
|
|
72
|
+
const t = String(s || '')
|
|
73
|
+
const i = t.indexOf('{')
|
|
74
|
+
const j = t.lastIndexOf('}')
|
|
75
|
+
if (i < 0 || j <= i) return null
|
|
76
|
+
try { return JSON.parse(t.slice(i, j + 1)) } catch { return null }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function describe(file) {
|
|
80
|
+
const b64 = readFileSync(file).toString('base64')
|
|
81
|
+
const ac = new AbortController()
|
|
82
|
+
const timer = setTimeout(() => ac.abort(), 90_000)
|
|
83
|
+
try {
|
|
84
|
+
// 走 /api/chat:只有这个端点认 `think: false`(/api/generate 在 0.40 上会被忽略,
|
|
85
|
+
// 结果思考把 num_predict 吃光、response 变成空串 —— 实测踩过)。
|
|
86
|
+
const r = await fetch(`${OLLAMA}/api/chat`, {
|
|
87
|
+
method: 'POST',
|
|
88
|
+
headers: { 'content-type': 'application/json' },
|
|
89
|
+
signal: ac.signal,
|
|
90
|
+
body: JSON.stringify({
|
|
91
|
+
model: MODEL,
|
|
92
|
+
think: false,
|
|
93
|
+
stream: false,
|
|
94
|
+
messages: [{ role: 'user', content: PROMPT, images: [b64] }],
|
|
95
|
+
format: 'json',
|
|
96
|
+
options: { temperature: 0.2, num_predict: 1400 },
|
|
97
|
+
}),
|
|
98
|
+
})
|
|
99
|
+
if (!r.ok) throw new Error('http ' + r.status)
|
|
100
|
+
const j = await r.json()
|
|
101
|
+
return parseJson(j?.message?.content)
|
|
102
|
+
} finally {
|
|
103
|
+
clearTimeout(timer)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function writeIndex(data) {
|
|
108
|
+
const tmp = INDEX + '.tmp'
|
|
109
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')
|
|
110
|
+
renameSync(tmp, INDEX)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function main() {
|
|
114
|
+
const data = JSON.parse(readFileSync(INDEX, 'utf8').replace(/^\uFEFF/, ''))
|
|
115
|
+
const items = Array.isArray(data) ? data : data.items
|
|
116
|
+
const todo = items.filter(needsWork)
|
|
117
|
+
console.log(`[sticker] 共 ${items.length} 张,待补 ${todo.length} 张,模型 ${MODEL}`)
|
|
118
|
+
const auditBefore = auditItems(items)
|
|
119
|
+
console.log(`[sticker] 打标前:情绪覆盖 ${auditBefore.emotionCoverage}% / schema ${SCHEMA_VERSION} 缺 ${auditBefore.missingSchema}`)
|
|
120
|
+
if (DRY) {
|
|
121
|
+
for (const it of todo.slice(0, 40)) console.log(' -', it.id, it.ext, (it.tags || []).join('/'))
|
|
122
|
+
return
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let ok = 0
|
|
126
|
+
let fail = 0
|
|
127
|
+
const queue = LIMIT > 0 ? todo.slice(0, LIMIT) : todo
|
|
128
|
+
for (const it of queue) {
|
|
129
|
+
const file = fileOf(it)
|
|
130
|
+
if (!file) { fail += 1; console.log(`[skip] ${it.id} 找不到图片文件`); continue }
|
|
131
|
+
try {
|
|
132
|
+
const j = await describe(file)
|
|
133
|
+
if (!j) { fail += 1; console.log(`[fail] ${it.id} 模型没吐 JSON`); continue }
|
|
134
|
+
const emo = Array.isArray(j.emotion) ? j.emotion : String(j.emotion || '').split(/[,,、\s]+/)
|
|
135
|
+
const scn = Array.isArray(j.scene) ? j.scene : String(j.scene || '').split(/[,,、\s]+/)
|
|
136
|
+
const act = Array.isArray(j.action) ? j.action : String(j.action || '').split(/[,,、\s]+/)
|
|
137
|
+
applyTagSchema(it, {
|
|
138
|
+
emotion: emo.join(','), scene: scn.join(','), action: act.join(','),
|
|
139
|
+
intensity: String(j.intensity || 'mid').toLowerCase(),
|
|
140
|
+
platform: it.facets?.platform || 'both',
|
|
141
|
+
merge: false,
|
|
142
|
+
})
|
|
143
|
+
if (j.desc) it.desc = String(j.desc).slice(0, 120)
|
|
144
|
+
it.needsDescribe = false
|
|
145
|
+
it.facetSource = 'local-vl'
|
|
146
|
+
it.tagUpdatedAt = Date.now()
|
|
147
|
+
ok += 1
|
|
148
|
+
writeIndex(data) // 每张都落盘:跑到一半被打断也不丢
|
|
149
|
+
const f = facetsOf(it)
|
|
150
|
+
console.log(`[ok ${ok}] ${it.id} ${f.emotion.join('/') || '-'} ${f.scene.join('/') || '-'} ${f.action.join('/') || '-'}`)
|
|
151
|
+
} catch (e) {
|
|
152
|
+
fail += 1
|
|
153
|
+
console.log(`[fail] ${it.id} ${e instanceof Error ? e.message : String(e)}`)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
writeIndex(data)
|
|
157
|
+
const after = auditItems(items)
|
|
158
|
+
console.log(`[sticker] 完成:成功 ${ok} / 失败 ${fail};情绪覆盖 ${after.emotionCoverage}%,缺 schema ${after.missingSchema}`)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
main().catch((e) => { console.error('[sticker] 致命:', e); process.exit(1) })
|
|
Binary file
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
gguf-quantize.py — 把 f16 的 GGUF 量化成 Q4_K_M 风格(纯 Python,不依赖 llama-quantize.exe)
|
|
5
|
+
|
|
6
|
+
为什么需要它(2026-12-03 实测踩到的坑):
|
|
7
|
+
· ollama 0.40 在 Windows 上 `create --quantize` 只认 safetensors,而 safetensors
|
|
8
|
+
导入路径又会调 MLX(苹果的库),Windows 上直接报 "MLX runtime is not available"
|
|
9
|
+
· GitHub releases 不可达,下不到官方 llama-quantize.exe
|
|
10
|
+
所以自己按 llama.cpp 的 Q4_K_M 规则重排一遍张量:大部分权重 Q4_K,
|
|
11
|
+
少量敏感层(attn_v / ffn_down / output / token_embd)Q6_K,norm 保持 F32。
|
|
12
|
+
|
|
13
|
+
用法:
|
|
14
|
+
python scripts/train/gguf-quantize.py --src E:/AI/models/muu-8b-f16.gguf --dst E:/AI/models/muu-8b-q4km.gguf
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
sys.path.insert(0, r'E:\AI\tools\llama.cpp-master\gguf-py')
|
|
24
|
+
|
|
25
|
+
from gguf import GGUFReader, GGUFWriter, GGMLQuantizationType as QT, GGUFValueType, quants # noqa: E402
|
|
26
|
+
|
|
27
|
+
QK = QT.Q8_0
|
|
28
|
+
QS = QT.Q8_0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def pick_qtype(name: str, data: np.ndarray, qt: QT = QT.Q8_0) -> QT | None:
|
|
32
|
+
"""返回量化类型;None 表示保持原样(norm 这类 1D 权重)。
|
|
33
|
+
|
|
34
|
+
可选 Q8_0(默认,8.7GB,质量≈f16)或 Q4_0(4.6GB,给 16G 内存的
|
|
35
|
+
核显笔记本用)。Q4_K/Q6_K 的量化器在 gguf 的 Python 实现里不存在,
|
|
36
|
+
ollama 0.40 在 Windows 上又不许对 GGUF 做 create 时量化,所以只能二选一。
|
|
37
|
+
"""
|
|
38
|
+
if data.ndim < 2:
|
|
39
|
+
return None
|
|
40
|
+
if data.shape[-1] % 32 != 0:
|
|
41
|
+
return None
|
|
42
|
+
return qt
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main():
|
|
46
|
+
ap = argparse.ArgumentParser()
|
|
47
|
+
ap.add_argument('--src', required=True)
|
|
48
|
+
ap.add_argument('--dst', required=True)
|
|
49
|
+
ap.add_argument('--qtype', default='Q8_0', help='Q8_0(默认)或 Q4_0(小内存设备)')
|
|
50
|
+
a = ap.parse_args()
|
|
51
|
+
qt_main = QT.Q8_0 if str(a.qtype).upper() == 'Q8_0' else QT.Q4_0
|
|
52
|
+
|
|
53
|
+
r = GGUFReader(a.src)
|
|
54
|
+
arch = r.get_field('general.architecture').contents()
|
|
55
|
+
w = GGUFWriter(a.dst, arch)
|
|
56
|
+
|
|
57
|
+
print('[1/3] 复制 metadata')
|
|
58
|
+
for field in r.fields.values():
|
|
59
|
+
if field.name == 'general.architecture' or field.name.startswith('GGUF.'):
|
|
60
|
+
continue
|
|
61
|
+
vt = field.types[0]
|
|
62
|
+
sub = field.types[-1] if vt == GGUFValueType.ARRAY else None
|
|
63
|
+
w.add_key_value(field.name, field.contents(), vt, sub_type=sub)
|
|
64
|
+
|
|
65
|
+
print('[2/3] 量化张量(Q4_K / Q6_K,norm 保持 F32)')
|
|
66
|
+
stats = {'q4': 0, 'q6': 0, 'keep': 0}
|
|
67
|
+
for i, t in enumerate(r.tensors):
|
|
68
|
+
data = t.data
|
|
69
|
+
qt = pick_qtype(t.name, data, qt_main)
|
|
70
|
+
if qt is None:
|
|
71
|
+
w.add_tensor(t.name, data, raw_dtype=t.tensor_type)
|
|
72
|
+
stats['keep'] += 1
|
|
73
|
+
else:
|
|
74
|
+
# 注意:不要传 raw_shape=原始形状 —— add_tensor_info 期望的是
|
|
75
|
+
# 「量化后每行的字节数」,传逻辑形状会报 "not a multiple of type size"。
|
|
76
|
+
# 直接用 qd.shape(已按 block 压缩)交给它自己换算回逻辑形状。
|
|
77
|
+
qd = quants.quantize(data, qt)
|
|
78
|
+
w.add_tensor(t.name, qd, raw_dtype=qt)
|
|
79
|
+
stats['q6' if qt == QS else 'q4'] += 1
|
|
80
|
+
if i % 50 == 0:
|
|
81
|
+
print(f' ...{i}/{len(r.tensors)} {t.name}', flush=True)
|
|
82
|
+
|
|
83
|
+
print('[3/3] 写盘(约 5GB)')
|
|
84
|
+
w.write_header_to_file()
|
|
85
|
+
w.write_kv_data_to_file()
|
|
86
|
+
w.write_tensors_to_file()
|
|
87
|
+
w.close()
|
|
88
|
+
print('DONE', a.dst, stats)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == '__main__':
|
|
92
|
+
main()
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
gguf-to-hf.py — 把 ollama 里的 GGUF 反量化回 HF safetensors(只为微调用)
|
|
5
|
+
|
|
6
|
+
为什么需要它(2026-12-03 实测):
|
|
7
|
+
huihui-ai/Qwen3-8B-abliterated 在 HF 上是 gated(要申请),hf-mirror 全超时,
|
|
8
|
+
modelscope 没有镜像 —— 唯一拿得到的 abliterated 权重,就是 ollama 里已经
|
|
9
|
+
下好的 Q4_K_M。Q4_K 反量化到 f16 的精度损失很小(8B 上约 1%),
|
|
10
|
+
再用 QLoRA 训出来的模型,人味(不端着、不拒答)这部分特性是保住的。
|
|
11
|
+
|
|
12
|
+
用法:
|
|
13
|
+
python scripts/train/gguf-to-hf.py --gguf <blob> --meta E:/AI/models/Qwen3-8B-meta --out E:/AI/models/Qwen3-8B-abliterated-hf
|
|
14
|
+
python scripts/train/gguf-to-hf.py --gguf <blob> --list # 只看 tensor 名,验证映射
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import shutil
|
|
22
|
+
import sys
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def map_name(n: str) -> str | None:
|
|
28
|
+
"""GGUF(llama.cpp 命名)→ HF(transformers 命名)"""
|
|
29
|
+
if n == 'token_embd.weight':
|
|
30
|
+
return 'model.embed_tokens.weight'
|
|
31
|
+
if n == 'output_norm.weight':
|
|
32
|
+
return 'model.norm.weight'
|
|
33
|
+
if n == 'output.weight':
|
|
34
|
+
return 'lm_head.weight'
|
|
35
|
+
if not n.startswith('blk.'):
|
|
36
|
+
return None
|
|
37
|
+
parts = n.split('.')
|
|
38
|
+
i = parts[1]
|
|
39
|
+
rest = '.'.join(parts[2:])
|
|
40
|
+
table = {
|
|
41
|
+
'attn_q.weight': 'self_attn.q_proj.weight',
|
|
42
|
+
'attn_k.weight': 'self_attn.k_proj.weight',
|
|
43
|
+
'attn_v.weight': 'self_attn.v_proj.weight',
|
|
44
|
+
'attn_output.weight': 'self_attn.o_proj.weight',
|
|
45
|
+
'attn_q_norm.weight': 'self_attn.q_norm.weight',
|
|
46
|
+
'attn_k_norm.weight': 'self_attn.k_norm.weight',
|
|
47
|
+
'attn_norm.weight': 'input_layernorm.weight',
|
|
48
|
+
'ffn_norm.weight': 'post_attention_layernorm.weight',
|
|
49
|
+
'ffn_gate.weight': 'mlp.gate_proj.weight',
|
|
50
|
+
'ffn_up.weight': 'mlp.up_proj.weight',
|
|
51
|
+
'ffn_down.weight': 'mlp.down_proj.weight',
|
|
52
|
+
}
|
|
53
|
+
if rest not in table:
|
|
54
|
+
return None
|
|
55
|
+
return f'model.layers.{i}.{table[rest]}'
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def main():
|
|
59
|
+
ap = argparse.ArgumentParser()
|
|
60
|
+
ap.add_argument('--gguf', required=True)
|
|
61
|
+
ap.add_argument('--meta', default='E:/AI/models/Qwen3-8B-meta')
|
|
62
|
+
ap.add_argument('--out', default='E:/AI/models/Qwen3-8B-abliterated-hf')
|
|
63
|
+
ap.add_argument('--list', action='store_true')
|
|
64
|
+
a = ap.parse_args()
|
|
65
|
+
|
|
66
|
+
from gguf import GGUFReader, quants
|
|
67
|
+
import torch
|
|
68
|
+
from safetensors.torch import save_file
|
|
69
|
+
|
|
70
|
+
print('[1/4] 打开 GGUF(5GB,映射不读全量)')
|
|
71
|
+
r = GGUFReader(a.gguf, 'r')
|
|
72
|
+
print(' tensors =', len(r.tensors))
|
|
73
|
+
|
|
74
|
+
if a.list:
|
|
75
|
+
for t in r.tensors[:40]:
|
|
76
|
+
print(f' {t.name:38s} {str(t.tensor_type):16s} {list(t.shape)}')
|
|
77
|
+
unknown = [t.name for t in r.tensors if map_name(t.name) is None]
|
|
78
|
+
print('未映射:', unknown[:10], '共', len(unknown))
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
print('[2/4] 反量化 + 改名(16GB 内存,约 3~6 分钟)')
|
|
82
|
+
out = {}
|
|
83
|
+
for k, t in enumerate(r.tensors):
|
|
84
|
+
hf = map_name(t.name)
|
|
85
|
+
if hf is None:
|
|
86
|
+
print(' [skip]', t.name)
|
|
87
|
+
continue
|
|
88
|
+
arr = t.data
|
|
89
|
+
if t.tensor_type.name.startswith('Q'):
|
|
90
|
+
arr = quants.dequantize(arr, t.tensor_type) # → float32
|
|
91
|
+
w = torch.from_numpy(np.asarray(arr, dtype=np.float32).copy()).to(torch.float16)
|
|
92
|
+
if t.name == 'token_embd.weight' and 'lm_head.weight' not in out:
|
|
93
|
+
out['lm_head.weight'] = w.clone()
|
|
94
|
+
out[hf] = w
|
|
95
|
+
if k % 60 == 0:
|
|
96
|
+
print(f' ...{k}/{len(r.tensors)}', flush=True)
|
|
97
|
+
|
|
98
|
+
print('[3/4] 写 safetensors')
|
|
99
|
+
os.makedirs(a.out, exist_ok=True)
|
|
100
|
+
save_file(out, os.path.join(a.out, 'model.safetensors'), metadata={'format': 'pt'})
|
|
101
|
+
|
|
102
|
+
print('[4/4] 拷 config / tokenizer(同词表,直接复用 Qwen3-8B 的)')
|
|
103
|
+
for fn in os.listdir(a.meta):
|
|
104
|
+
if fn.endswith(('.json', '.txt', '.jinja', '.model')) and not fn.startswith('model') and fn != 'model.safetensors.index.json':
|
|
105
|
+
src = os.path.join(a.meta, fn)
|
|
106
|
+
if os.path.isfile(src):
|
|
107
|
+
shutil.copy2(src, os.path.join(a.out, fn))
|
|
108
|
+
print('DONE →', a.out, ' 文件数', len(os.listdir(a.out)))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == '__main__':
|
|
112
|
+
main()
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
merge-lora.py — 把训练好的 LoRA 合并回基座,产出可直接转 GGUF 的 f16 权重
|
|
5
|
+
|
|
6
|
+
为什么在 CPU 上合并:基座 bf16/f16 是 16GB,显卡只剩不到 5GB 余量,
|
|
7
|
+
放 GPU 会 OOM;CPU 合并慢几分钟但稳。
|
|
8
|
+
|
|
9
|
+
用法(WSL):
|
|
10
|
+
/opt/train/bin/python scripts/train/merge-lora.py \
|
|
11
|
+
--base /opt/models/Qwen3-8B-abliterated-hf \
|
|
12
|
+
--lora /opt/train/out \
|
|
13
|
+
--out /mnt/e/AI/models/Qwen3-8B-muu-merged
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import os
|
|
19
|
+
|
|
20
|
+
import torch
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def main():
|
|
24
|
+
ap = argparse.ArgumentParser()
|
|
25
|
+
ap.add_argument('--base', default='/opt/models/Qwen3-8B-abliterated-hf')
|
|
26
|
+
ap.add_argument('--lora', default='/opt/train/out')
|
|
27
|
+
ap.add_argument('--out', default='/mnt/e/AI/models/Qwen3-8B-muu-merged')
|
|
28
|
+
a = ap.parse_args()
|
|
29
|
+
|
|
30
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
31
|
+
from peft import PeftModel
|
|
32
|
+
|
|
33
|
+
print('[1/3] 读 tokenizer')
|
|
34
|
+
tok = AutoTokenizer.from_pretrained(a.base, trust_remote_code=True)
|
|
35
|
+
|
|
36
|
+
print('[2/3] CPU 加载基座(16GB)+ 合并 LoRA')
|
|
37
|
+
base = AutoModelForCausalLM.from_pretrained(
|
|
38
|
+
a.base, torch_dtype=torch.float16, device_map='cpu', trust_remote_code=True, low_cpu_mem_usage=True,
|
|
39
|
+
)
|
|
40
|
+
model = PeftModel.from_pretrained(base, a.lora, device_map='cpu')
|
|
41
|
+
model = model.merge_and_unload()
|
|
42
|
+
|
|
43
|
+
print('[3/3] 保存(分片 4GB)')
|
|
44
|
+
os.makedirs(a.out, exist_ok=True)
|
|
45
|
+
model.save_pretrained(a.out, safe_serialization=True, max_shard_size='4GB')
|
|
46
|
+
tok.save_pretrained(a.out)
|
|
47
|
+
print('DONE →', a.out)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == '__main__':
|
|
51
|
+
main()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# probe-mirrors.sh — 测各 pypi 镜像对 nvidia 运行库的真实下载速度(决定换不换源)
|
|
3
|
+
set -u
|
|
4
|
+
|
|
5
|
+
for host in "https://pypi.tuna.tsinghua.edu.cn" "https://mirrors.aliyun.com/pypi" "https://pypi.org" "https://mirrors.cloud.tencent.com/pypi"; do
|
|
6
|
+
u=$(curl -s --max-time 12 "$host/simple/nvidia-cudnn-cu12/" | grep -o 'https://[^"#]*\.whl' | tail -1)
|
|
7
|
+
if [ -z "$u" ]; then
|
|
8
|
+
echo "$host -> 取包地址失败"
|
|
9
|
+
continue
|
|
10
|
+
fi
|
|
11
|
+
curl -s -o /dev/null --max-time 10 -w "$host -> %{speed_download} B/s\n" "$u"
|
|
12
|
+
done
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# probe-mirrors2.sh — simple 页面里是相对路径,拼上 host 再测;顺便测 conda 镜像
|
|
3
|
+
set -u
|
|
4
|
+
|
|
5
|
+
for host in "https://pypi.tuna.tsinghua.edu.cn" "https://mirrors.aliyun.com/pypi" "https://mirrors.cloud.tencent.com/pypi"; do
|
|
6
|
+
path=$(curl -s --max-time 12 "$host/simple/nvidia-cudnn-cu12/" | grep -o '/packages/[^"#]*\.whl' | tail -1)
|
|
7
|
+
if [ -z "$path" ]; then
|
|
8
|
+
echo "$host -> 取包地址失败"
|
|
9
|
+
continue
|
|
10
|
+
fi
|
|
11
|
+
curl -s -o /dev/null --max-time 10 -w "$host -> %{speed_download} B/s\n" "$host$path"
|
|
12
|
+
done
|
|
13
|
+
|
|
14
|
+
# conda(pytorch) 镜像上 pytorch-cuda 包的速度
|
|
15
|
+
u=$(curl -s --max-time 12 "https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/linux-64/" | grep -o 'pytorch-2\.5\.1[^"#]*\.conda' | tail -1)
|
|
16
|
+
if [ -n "$u" ]; then
|
|
17
|
+
curl -s -o /dev/null --max-time 10 -w "tuna_conda -> %{speed_download} B/s\n" "https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/linux-64/$u"
|
|
18
|
+
else
|
|
19
|
+
echo "tuna_conda -> 取包地址失败"
|
|
20
|
+
fi
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# setup-wsl.sh — 在 WSL(Ubuntu) 里一次装好 8B QLoRA 训练所需环境
|
|
3
|
+
# 用法(在 Windows 里):wsl -d Ubuntu -u root -- bash /mnt/f/qqbot/scripts/train/setup-wsl.sh
|
|
4
|
+
set -e
|
|
5
|
+
|
|
6
|
+
PY=/opt/train/bin/pip
|
|
7
|
+
if [ ! -x "$PY" ]; then
|
|
8
|
+
python3 -m venv /opt/train
|
|
9
|
+
fi
|
|
10
|
+
|
|
11
|
+
# torch 走官方源:实测 6MB/s;清华源会断流
|
|
12
|
+
"$PY" install -q --upgrade pip -i https://mirrors.aliyun.com/pypi/simple/
|
|
13
|
+
"$PY" install -q torch==2.5.1+cu121 --index-url https://download.pytorch.org/whl/cu121
|
|
14
|
+
"$PY" install -q transformers==4.57.6 datasets==3.6.0 peft trl accelerate bitsandbytes \
|
|
15
|
+
-i https://mirrors.aliyun.com/pypi/simple/
|
|
16
|
+
|
|
17
|
+
/opt/train/bin/python - <<'EOF'
|
|
18
|
+
import torch
|
|
19
|
+
print('TORCH_OK', torch.__version__, 'cuda:', torch.cuda.is_available(),
|
|
20
|
+
torch.cuda.get_device_name(0) if torch.cuda.is_available() else '')
|
|
21
|
+
import transformers, trl, peft
|
|
22
|
+
print('LIB_OK', transformers.__version__, trl.__version__, peft.__version__)
|
|
23
|
+
EOF
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# setup-wsl2.sh — 网络抖的时候用:先 curl 断点续传把 torch wheel 拉到本地,再离线装
|
|
3
|
+
set -e
|
|
4
|
+
|
|
5
|
+
WHL=/opt/torch-2.5.1-cu121.whl
|
|
6
|
+
URL='https://download.pytorch.org/whl/cu121/torch-2.5.1%2Bcu121-cp312-cp312-linux_x86_64.whl'
|
|
7
|
+
|
|
8
|
+
for i in 1 2 3 4 5 6 7 8 9 10; do
|
|
9
|
+
curl -L -C - --retry 5 --retry-delay 2 --connect-timeout 15 -o "$WHL" "$URL" && break
|
|
10
|
+
echo "retry $i ..."
|
|
11
|
+
sleep 3
|
|
12
|
+
done
|
|
13
|
+
|
|
14
|
+
ls -lh "$WHL"
|
|
15
|
+
/opt/train/bin/pip install -q "$WHL"
|
|
16
|
+
/opt/train/bin/pip install -q transformers==4.57.6 datasets==3.6.0 peft trl accelerate bitsandbytes \
|
|
17
|
+
-i https://mirrors.aliyun.com/pypi/simple/
|
|
18
|
+
|
|
19
|
+
/opt/train/bin/python - <<'EOF'
|
|
20
|
+
import torch
|
|
21
|
+
print('TORCH_OK', torch.__version__, 'cuda:', torch.cuda.is_available(),
|
|
22
|
+
torch.cuda.get_device_name(0) if torch.cuda.is_available() else '')
|
|
23
|
+
import transformers, trl, peft
|
|
24
|
+
print('LIB_OK', transformers.__version__, trl.__version__, peft.__version__)
|
|
25
|
+
EOF
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# setup-wsl3.sh — wheel 已下到 /opt(文件名被 curl 改过),改名后离线装 + 装其余依赖
|
|
3
|
+
set -e
|
|
4
|
+
|
|
5
|
+
cd /opt
|
|
6
|
+
if [ -f torch-2.5.1-cu121.whl ]; then
|
|
7
|
+
mv -f torch-2.5.1-cu121.whl 'torch-2.5.1+cu121-cp312-cp312-linux_x86_64.whl'
|
|
8
|
+
fi
|
|
9
|
+
|
|
10
|
+
/opt/train/bin/pip install -q '/opt/torch-2.5.1+cu121-cp312-cp312-linux_x86_64.whl' \
|
|
11
|
+
-i https://mirrors.aliyun.com/pypi/simple/
|
|
12
|
+
|
|
13
|
+
/opt/train/bin/pip install -q transformers==4.57.6 datasets==3.6.0 peft trl accelerate bitsandbytes \
|
|
14
|
+
-i https://mirrors.aliyun.com/pypi/simple/
|
|
15
|
+
|
|
16
|
+
/opt/train/bin/python - <<'EOF'
|
|
17
|
+
import torch
|
|
18
|
+
print('TORCH_OK', torch.__version__, 'cuda:', torch.cuda.is_available(),
|
|
19
|
+
torch.cuda.get_device_name(0) if torch.cuda.is_available() else '')
|
|
20
|
+
import transformers, trl, peft
|
|
21
|
+
print('LIB_OK', transformers.__version__, trl.__version__, peft.__version__)
|
|
22
|
+
EOF
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# setup-wsl4.sh — 换清华源重装(实测 9.3MB/s,阿里只有 1.1MB/s 且会断流)
|
|
3
|
+
set -e
|
|
4
|
+
|
|
5
|
+
pkill -9 -f '/opt/train/bin/pip' 2>/dev/null || true
|
|
6
|
+
sleep 1
|
|
7
|
+
|
|
8
|
+
/opt/train/bin/pip install --no-input -q \
|
|
9
|
+
'/opt/torch-2.5.1+cu121-cp312-cp312-linux_x86_64.whl' \
|
|
10
|
+
-i https://pypi.tuna.tsinghua.edu.cn/simple/
|
|
11
|
+
|
|
12
|
+
/opt/train/bin/pip install --no-input -q \
|
|
13
|
+
transformers==4.57.6 datasets==3.6.0 peft trl accelerate bitsandbytes \
|
|
14
|
+
-i https://pypi.tuna.tsinghua.edu.cn/simple/
|
|
15
|
+
|
|
16
|
+
/opt/train/bin/python - <<'EOF'
|
|
17
|
+
import torch
|
|
18
|
+
print('TORCH_OK', torch.__version__, 'cuda:', torch.cuda.is_available(),
|
|
19
|
+
torch.cuda.get_device_name(0) if torch.cuda.is_available() else '')
|
|
20
|
+
import transformers, trl, peft
|
|
21
|
+
print('LIB_OK', transformers.__version__, trl.__version__, peft.__version__)
|
|
22
|
+
EOF
|