698 MB 的硬骨头:Quyet-1.0-Tiny 境内下载排障全记录
698 MB 的硬骨头:Quyet-1.0-Tiny 境内下载排障全记录
上一篇写完 Quyet-1.0 系列"能不能本地部署",结论是可以——Small-EN 153M、Tiny 183M 都是 CPU 就能跑的编码器,比 31.3B 的 Large 现实得多。
于是我去把 Tiny 的权重下下来。714.6 MB,跑了将近 3 小时,中间经历了:客户端卡死在 0 字节、镜像限速到 1 KB/s、
416刷屏、以及最恶心的一种——文件"下完了",尺寸也对,但 sha256 不对。这篇把四个坑、证据链和最终可复用的下载器都记下来。结论是:在不可靠的镜像上做大文件下载,"下完"和"下对"之间隔着一整套校验设计。
最后还得回答一个问题:哈希对上就代表能用吗?于是装上运行时跑了冒烟测试——这份权重确实能跑,而且有判别力(详见第十节)。
先说结论
| 问题 | 结论 |
|---|---|
| 目标模型 | chinhnc/Quyet-1.0-Tiny,183M 编码器(decision model),Apache 许可,仓库带官方 MANIFEST.sha256 |
| 最终结果 | 698 MB 权重 + 8 个文件全部落盘并通过 sha256 校验,两套独立工具互验一致 |
| 可用性验证 | 装上运行时跑通冒烟测试:三组概率均归一化,自造 5 条用例命中 4 条,热启动 62 ms/请求(CPU) |
| 网络前提 | 这台机器直连 huggingface.co 超时,hf-mirror.com 可用 → 全程走镜像 |
| 坑一 | huggingface_hub 走镜像时卡死在 0 字节,.incomplete 文件十分钟不涨 |
| 坑二 | 镜像的分段请求会偶发忽略 Range 头,返回 200 + 整个文件——不校验就会静默写错字节 |
| 坑三 | 多线程共用一个缓冲文件句柄做 seek+write,写入位置互相踩踏;同期还观测到互相矛盾的尺寸(853 MB / 0 B) |
| 坑四 | 并发一高就被限速/回 416;重试风暴会让情况更糟,必须退避 + 降并发 |
| 代价 | 理论传输时间约 12 分钟(按 1 MB/s),实际耗时约 3 小时,其中一次 698 MB 全量重下 |
| 一句话 | 分块下载 + 断点续传 + Content-Range 校验 + 全文件 sha256 复核,四件套缺一不可 |
一、环境与前提
| 项目 | 值 |
|---|---|
| 系统 | Windows 10.0.26100(PowerShell 5.1.26100.9444) |
| Python | 3.12.9(Miniconda3) |
huggingface_hub |
1.32.0(无 hf / huggingface-cli 命令) |
| 磁盘 | C: 剩余 7.9 GB,D: 剩余 533 GB → 落盘选 D:\models\Quyet-1.0-Tiny |
| 工具 | aria2c 未安装,curl 8.21 / wget 可用 |
连通性实测(Invoke-WebRequest 计时):
| 目标 | 结果 |
|---|---|
https://huggingface.co |
12.0 s 超时(不可用) |
https://hf-mirror.com |
684 ms,可用 |
https://github.com |
2.96 s,可用 |
https://pypi.org |
1.58 s,可用 |
模型本身来自 Hugging Face chinhnc/Quyet-1.0-Tiny,运行时是 GitHub ncchinh/quyet。仓库文件清单:
model.safetensors 731,715,172 B (697.82 MB)
tokenizer.json 17,525,329 B ( 16.71 MB)
tokenizer_config.json 46,440 B
LICENSE / NOTICE / README.md / quyet_config.json
special_tokens_map.json / MANIFEST.sha256 / .gitattributes
注意最后那个 MANIFEST.sha256——它是这次排障里唯一可信的裁判,后面所有"下对了没有"的判断都靠它。
顺带排除的备选路径:ModelScope 的检索未返回该模型;SJTU 镜像、Gitee 的 HF 代理路径按常见约定拼出的 URL 均返回 404(这两条属试探性结论,未拿到官方路径文档)。能确认可用的实际上只有 hf-mirror.com 一条路。
二、坑一:huggingface_hub 卡死在 0 字节
第一反应当然是用官方姿势:
$env:HF_ENDPOINT = "https://hf-mirror.com"
python -c "from huggingface_hub import snapshot_download; snapshot_download('chinhnc/Quyet-1.0-Tiny', local_dir=r'D:\models\Quyet-1.0-Tiny')"
结果十分钟过去,目标目录里 .cache\huggingface\download\ 下两个 .incomplete 文件始终保持 0 字节:
0 KB ...49256c653c856...5ae52691.incomplete ← model.safetensors
0 KB ...197d4cc5406e...143dc7dc.incomplete ← tokenizer.json
但同一时刻,用 PowerShell 直接发一个 8 MB 的 Range 请求,能拿到数据(0.34 MB/s):
$req = [Net.HttpWebRequest]::Create("https://hf-mirror.com/$f")
$req.AddRange(0, 8388607); $req.Timeout = 30000; $resp = $req.GetResponse()
判断:不是"网断了",而是客户端这条路径卡住了。 镜像的 resolve 接口是个 302,跳到 cas-bridge.xethub.hf.co 上的签名 URL(Xet 桥,CloudFront 回源,签名有效期 1 小时);huggingface_hub 在这条链路上挂住,而手写的 Range 请求能正常走通。
处置:放弃官方客户端,自己写下载器。这一步也定下了后面的整个基调——要自己控制重试、分块和校验。
三、坑二:镜像会"假装"响应分段请求
这是最隐蔽、也是最终导致第一次全量失败的那个坑。
分块下载的前提是服务端支持 Range。正常情况下应该返回 206 Partial Content + Content-Range。实测大多数时候确实正常:
Range: bytes=0-1048575 → 206 Content-Range: bytes 0-1048575/731715172
Range: bytes=600000000- → 206 Content-Range: bytes 600000000-731715171/731715172
但偶发情况下,服务端会无视 Range,直接回 200 + 整个文件。 日志里能抓到现行:
! model.safetensors chunk 0 attempt 3: server ignored Range header -> retry in 5s
如果客户端天真地认为"我要的就是这段",就会把文件开头的字节写到这个分块该在的偏移上——文件长度、结构全都正常,只有内容是错的。这正是最难查的一类 bug:没有报错,没有崩溃,只有最后 sha256 对不上。
第一版下载器里的守卫写错了:
# ❌ 错误示范
if resp.status == 200 and cur > 0: # 只防了"续传时被忽略"
cur = 0
fh.seek(start + cur) # cur == 0 时照样把文件头写到 start 偏移
它漏掉了 cur == 0(首次请求)这个最常见的情况。
修复后的守卫,要求 Content-Range 的起点必须和请求的实际起点严格对齐:
# ✅ 正确做法
if resp.status == 206:
cr = resp.headers.get("Content-Range", "")
if not cr.startswith(f"bytes {start + cur}-"):
raise RuntimeError(f"unexpected Content-Range '{cr}'")
elif resp.status == 200:
if start + cur != 0 or span < total_size: # 只有"整文件单块下载"才允许 200
raise RuntimeError("server ignored Range header")
else:
raise RuntimeError(f"HTTP {resp.status}")
代价:第一次全量下完后 sha256 不匹配(实际 b3b89c8f… ≠ 期望 49256c65…),697.8 MB 全部作废重下。哪一段被写坏了根本无法定位,大文件一旦哈希不过,只能整份重来。
诚实交代归因边界:失败的那一轮跑的代码已经修掉了下面这个 v1 守卫 bug,所以"它就是罪魁"我不能这么说。我确定的只有两件事——这类"服务端不按约定返回"的行为确实在这条链路上出现过(有日志),以及补上 Content-Range 严格校验、整份重下之后,同样的文件一次通过。在无法定位坏块的前提下,把校验做到最严、然后重来,是唯一可靠的动作。
四、坑三:多线程共用一个缓冲文件句柄
第一版为了省事,八个分块线程共享同一个 open(fname, "r+b") 对象,各自 seek() 到自己的偏移再 write()。
这是错的。 Python 的缓冲文件对象持有单个文件位置和单个内部缓冲区,seek() 和 write() 是两个独立操作,中间会被其他线程插进来:
线程 A: seek(600 MB) ─┐
线程 B: seek(100 MB) ─┼─→ 实际写入位置是最后那个 seek 的结果
线程 A: write(...) ─┘
于是写入落到错误的偏移上,内容错位。当时的现场证据是一堆自相矛盾的尺寸:
| 文件 | 期望 | 实际观测到 |
|---|---|---|
model.safetensors |
731,715,172 B | Get-Item 报 853,635,988 B(比期望大 116 MB) |
| 同上 | — | 同一次列举中 Get-ChildItem 却报 0 B |
tokenizer.json |
17,525,329 B | 29,208,881 B,且多出的 11,683,552 B 恰好等于它的两个分块长度 |
需要说明的是:"文件长大"这一条我只能算工程推断,没能证死机制(见第十一节)。但"同一个文件在同一秒被报出 853 MB 和 0 B 两个尺寸"本身就是强信号——有不受控的并发写入正在发生,而共享缓冲句柄正好是当时唯一的嫌疑对象。
修复方案两条,都在第二版落地:
# ① 每个分块线程开自己的句柄,位置互不干扰
with open(fname, "r+b", buffering=0) as fh: # 线程私有
fh.seek(start + cur)
fh.write(buf)
# ② 续传安全地预分配:不能用 "wb"(会把已下数据清零)
if not os.path.exists(fname):
with open(fname, "ab") as fh:
fh.truncate(size)
else:
have = os.path.getsize(fname)
if have > size:
os.truncate(fname, size)
elif have < size:
with open(fname, "ab") as fh: # "ab" 只扩展、不清零
fh.truncate(size)
这里有个我自己踩了一脚的连带坑:重写时一度写成
open(fname, "wb")+truncate(size)来预分配——"wb"会先把文件截成 0,而断点续传的状态文件还记着"这些字节已经下好了",于是续传后拿到的是一堆零。发现后改成了上面的"ab"版本。预分配和续传是天生打架的一对,写的时候要一起想。
五、坑四:限速、416 与重试风暴
镜像的带宽行为很不稳定:
| 并发数 | 观测速度 |
|---|---|
| 单连接 | 0.30 – 0.60 MB/s |
| 4 连接 | 0.30 MB/s(聚合没变,说明被整体限流) |
| 8 连接 | 突发 2 – 3 MB/s,随后掉到 1 KB/s 并大量超时 |
典型症状是连接不断、但字节不涨(trickle)——socket 每几十秒挤一点数据,读写超时永远不触发,任务看起来"在跑",实际卡死。日志里出现过整整 24 分钟零进展。
解法一:卡死检测(不看超时,看速率)。 每 25 秒算一次窗口速率,低于 64 KB/s 就主动断开、重新取签名 URL 续传:
now = time.time()
if now - win_start >= STALL_WINDOW: # 25 s
rate = win_bytes / (now - win_start)
if rate < STALL_MIN_RATE: # 64 KB/s
raise RuntimeError(f"stalled at {rate/1024:.0f} KB/s - reconnecting")
win_start, win_bytes = now, 0
重连本身就能提速——每次重连都会重新走一遍 302,拿到新的签名 URL,常常又能享受一次突发带宽。这个机制上线后,日志变成了这样,进度只进不退:
! chunk 5 attempt 2: stalled at 60 KB/s - reconnecting for a fresh burst
progress 189.0/697.8 MB (27.1%) 1.02 MB/s eta 8.3 min
解法二:退避要给足,并发要降。 第一次全量失败后的重试阶段,六个分块以每 3 秒一次的频率猛敲镜像,结果换来的是连续几百条 HTTP Error 416: Requested Range Not Satisfiable(Range 本身完全合法,纯属被限流惩罚)。停手、等一会儿、把并发降到 4 路、退避改成 min(60, 4 + 2*attempt) 之后,同样的请求立刻恢复正常。
教训:面对限速,重试越猛恢复越慢。
六、最终下载器的设计要点
四个版本各自补上了什么,一张表看完:
| 版本 | 时间 | 改动 | 结果 |
|---|---|---|---|
| v0 官方客户端 | 11:47 | huggingface_hub + HF_ENDPOINT |
❌ 卡死 0 字节,放弃 |
| v1 自研首版 | 11:55 | 分块并发(8 路)+ 状态侧车 | ❌ 共享缓冲句柄;Range 守卫写错 |
| v2 | 12:35 | 每线程独立句柄、预分配、逐文件 sha256 | ⚠️ 捞回 183 MB,续传可用 |
| v3 | 12:47 | 卡死检测(25 s / 64 KB/s)+ 重连取新签名 URL | ⚠️ 下满 697.8 MB,但 sha256 不过 |
| v4 | 14:31 | 严格 Content-Range 校验、并发降到 4、退避放宽 |
✅ 整份重下,8/8 通过 |
完整可运行的脚本见文末附录(换仓库只需改开头三个常量)。核心是六条:
| 机制 | 作用 |
|---|---|
| 分块 + 每线程独立句柄 | 并发提速,且不互相踩位置 |
状态侧车文件(.dsh_download_state.json) |
每 5 秒落盘每个分块的字节进度,任意时刻可续传 |
"ab" + truncate() 预分配 |
续传时不清空已下数据 |
Content-Range 严格校验 |
拒绝被 200 冒充分段,从源头堵住静默损坏 |
| 25 秒 / 64 KB/s 卡死检测 + 重连 | 治 trickle,顺带靠新签名 URL 刷新带宽 |
| 逐文件 sha256 + 整目录复核,失败整份重试(最多 3 次) | 保证"下完"等于"下对" |
七、结果
[14:47:48] downloaded + verified model.safetensors (697.8 MB)
[14:47:48] final sha256 verification ...
[14:47:48] OK LICENSE
[14:47:48] OK NOTICE
[14:47:48] OK README.md
[14:47:49] OK model.safetensors
[14:47:49] OK quyet_config.json
[14:47:49] OK special_tokens_map.json
[14:47:49] OK tokenizer.json
[14:47:49] OK tokenizer_config.json
[14:47:49] ALL FILES VERIFIED OK
随后用另一套工具独立复核了一遍(下载器内置 hashlib vs PowerShell Get-FileHash):
| 文件 | 大小 | sha256 |
|---|---|---|
model.safetensors |
731,715,172 B | OK |
tokenizer.json |
17,525,329 B | OK |
tokenizer_config.json |
46,440 B | OK |
quyet_config.json |
2,565 B | OK |
special_tokens_map.json |
636 B | OK |
README.md / LICENSE / NOTICE |
3,161 / 11,343 / 1,846 B | OK |
8/8 与官方 MANIFEST.sha256 一致,目录总计 714.6 MB。
八、经验清单
| 症状 | 别急着归因于网络 | 正确的检测 | 修法 |
|---|---|---|---|
| 下载十分钟 0 字节 | "镜像挂了" | 手动发一个 Range 请求看能不能拿到数据 |
换客户端/自己写;302 后面的签名 URL 是常见卡点 |
| 文件大小对、sha256 不对 | "文件损坏了" | 打印每次响应的 status 和 Content-Range |
校验 Content-Range 起点;拒绝 200 冒充分段 |
| 文件比预期还大 | "磁盘出问题了" | 检查是否多线程共用了文件句柄 | 每线程独立句柄 + 预分配 |
| 进度条卡住但进程没死 | "再等等" | 算窗口速率而不是看超时 | 低速率主动断连重试 |
突然满屏 416 / 超时 |
"服务端坏了" | 看是不是自己重试太猛 | 降并发、加退避、停一会儿 |
| 续传后文件全是 0 | "状态文件坏了" | 检查预分配用的是 "wb" 还是 "ab" |
"ab" + truncate() |
最该带走的一条:凡是"下完没有报错"的结论,都必须有哈希背书。 这次如果没有仓库自带的 MANIFEST.sha256,我会拿到一个 697.8 MB、能加载、能跑、但结果是错的权重文件——而且大概率要等到模型表现莫名其妙的时候才会怀疑到它头上。
九、怎么用这份权重
import quyet
# 本地路径加载:不需要联网,也不受 HF 直连不通的影响
m = quyet.load(r"D:\models\Quyet-1.0-Tiny")
r = m.predict(
{"message": "Please close my card, I lost it yesterday."},
{"intent": {"type": "choice",
"instructions": "What does the customer want?",
"criteria": {"cancel": "close the card",
"limit": "change the limit",
"other": None}},
"urgent": {"type": "noul", "instructions": "The request is urgent."}},
)
print(r["answers"])
如果哪天需要按 repo id 加载(quyet.load("chinhnc/Quyet-1.0-Tiny"))触发联网,记得先设环境变量:
$env:HF_ENDPOINT = "https://hf-mirror.com"
十、冒烟测试:这份权重真的能跑吗
哈希对上只说明字节正确,不说明模型可用。于是装上官方运行时实测一遍(pip install quyet,走清华 PyPI 镜像):
| 项 | 值 |
|---|---|
| 装到的版本 | quyet 1.0.2、torch 2.14.1+cpu、transformers 5.19.0、safetensors 0.8.0 |
| 安装位置 | 用户级 site-packages(base 环境的 site-packages 不可写,pip 自动降级为 user 安装) |
| 磁盘占用 | user site-packages 共 2.52 GB,其中 torch 502 MB、transformers 100 MB |
| 加载方式 | quyet.load(r"D:\models\Quyet-1.0-Tiny"),全程 HF_HUB_OFFLINE=1,不联网 |
耗时(纯 CPU):
| 阶段 | 耗时 |
|---|---|
import quyet + import torch |
2.3 s |
quyet.load(...) 冷启动(读 698 MB 权重) |
17.8 s |
首次 predict |
205 ms |
热启动 predict(连续 5 次均值) |
62 ms |
README 自带例子的输出("客户说卡丢了要销卡" + intent / urgent / mood 三问):
"intent": { "choice": "other", "confidence": 0.5066,
"probabilities": { "cancel": 0.4074, "limit": 0.086, "other": 0.5066 } }
"urgent": { "noul": 0.4254, "confidence": 0.5746 }
"mood": { "score": 1.0657, "legend": { "0": "calm", "1": "annoyed", "2": "angry" },
"probabilities": { "0": 0.2387, "1": 0.4568, "2": 0.3044 } }
usage: 134 input tokens, 0 output tokens
三组概率都严格归一化到 1,输出结构完整、warnings 为空。权重是好的——这也反过来给前面那轮 sha256 校验盖了章。
但它准不准:判别力实测
"能出概率"和"出得对"是两件事。又写了 5 条带标注的用例:
| 输入 | 期望 | 实际 | P(期望) | 概率分布 |
|---|---|---|---|---|
| I lost my card yesterday, please close the account immediately. | cancel | cancel | 0.876 | cancel .876 / other .097 / limit .027 |
| Please raise my credit limit from 2000 to 5000. | limit | limit | 0.872 | limit .872 / other .101 / cancel .027 |
| What time does the branch open on Saturdays? | other | other | 0.875 | other .875 / cancel .066 / limit .060 |
| My card was stolen. Cancel it right now before someone uses it. | cancel | cancel | 0.659 | cancel .659 / other .307 / limit .034 |
| Can you lower my spending limit? It is too high for me. | limit | other | 0.342 | other .588 / limit .342 / cancel .071 |
4/5 命中,且明确用例的置信度都在 0.87 上下、次优选项只有 0.03–0.10——判别力是真的,不是噪声。最后一条我判它"错"其实偏苛刻:"把额度调低"算不算 change the limit 本身就有歧义,模型给的是 0.588 vs 0.342 的接近分布,属于合理的不确定。
一盆冷水
README 自带的那个例子,Tiny 版给的答案是 other(0.5066),而不是 cancel(0.4074)——"close my card" 明显该归到 cancel,所以这一条它答错了。合理解释:Tiny 是家族里最小的(183M),README 的例子多半是拿 Small / Small-EN 或更大模型调的。
结论:能跑通 ≠ 够准。 真要拿它做线上分流,建议先用 Small-EN(153M,英文专用)跑同样的用例对比后再定。
十一、存疑与未解
- 那两段"时间跳跃":日志里出现过 24 分钟和 8 分钟完全没有输出的空档,进程仍在、秒级日志线程也在跑,原因不明(疑似宿主环境挂起或磁盘元数据缓存异常)。这不影响最终结果,但意味着"日志没有输出"不等于"程序卡死",反之亦然。
- 尺寸元数据互相矛盾且有过冲:同一秒内
Get-Item报 853,635,988 B、Get-ChildItem报 0 B;tokenizer.json则稳定地被报成比代码写入量多 11.68 MB。我把这当作"文件正被不受控地并发写入"的信号,并据此改掉了共享句柄——但"写入越界"的确切机制没有被证死(所有seek目标都在文件范围内,理论上不该越界)。改完之后同样的文件一次通过哈希校验,这是最强的间接证据,但不是机理证明。 - 损坏区间的具体位置未知:第一次 sha256 失败后无法定位(除非逐块比对哈希并保留官方分块信息),所以只能整份重下。
- 没试过的选项:
hf_transfer多线程后端、aria2c多连接客户端(本机未安装)、以及换用代理直连官方源。如果哪天要常态化下大模型,这几个值得再评估。
数据来源
| 来源 | 用途 | 时间 |
|---|---|---|
Hugging Face chinhnc/Quyet-1.0-Tiny |
模型规格、文件清单、官方 MANIFEST.sha256 |
2026-10-10 读取 |
https://hf-mirror.com/api/models/chinhnc/Quyet-1.0-Tiny?blobs=true |
权威文件尺寸(731715172 / 17525329) |
2026-10-10 读取 |
MANIFEST.sha256(仓库内) |
全部 8 个文件的 sha256 基准 | 2026-10-10 读取 |
GitHub ncchinh/quyet |
家族规格、quyet.load 用法、问题类型定义 |
2026-10-10 读取 |
PyPI quyet |
运行时版本、依赖(torch>=2.4、transformers>=5.17)、wheel 体积 |
2026-10-10 读取 |
| 本机下载器日志 | 全部时间戳、错误与速率数据 | 2026-10-10 11:55 – 14:47 |
免责声明
本文记录的是特定机器、特定时段、特定镜像状态下的实测结果。镜像的限速与 416 行为随时间变化,huggingface_hub 卡死的现象也可能与版本或网络路径有关,不构成对任何服务的稳定性结论。文中的"根因"均有日志或哈希证据支撑,但涉及并发写入与文件系统元数据的部分属于工程推断。第十节的冒烟测试为笔者自造的 5 条小样本用例,仅用于验证权重可用性与判别力,不构成模型能力评测,不代表其在真实业务分布上的准确率。模型许可与使用限制请以仓库原文为准。
附录:完整下载器脚本
一次性脚本,用后即删,此处留档。换仓库只需改开头三个常量(REPO / ENDPOINT / TARGET)。已验证可跑通 chinhnc/Quyet-1.0-Tiny 全量下载 + 校验。
"""Resumable parallel downloader for a Hugging Face repo via mirror.
Each chunk worker uses its OWN file handle (a shared buffered handle races on
seek/write and corrupts offsets), files are preallocated resume-safely, range
support is validated, and every file is sha256-verified against
MANIFEST.sha256 with retries.
"""
import hashlib
import json
import os
import sys
import threading
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
REPO = "chinhnc/Quyet-1.0-Tiny"
ENDPOINT = "https://hf-mirror.com"
TARGET = r"D:\models\Quyet-1.0-Tiny"
WORKERS_PER_FILE = 4
MAX_FILES_PARALLEL = 3
CHUNK_MIN = 8 * 1024 * 1024
READ_TIMEOUT = 15
STALL_WINDOW = 25
STALL_MIN_RATE = 64 * 1024
MAX_RETRIES = 200
FILE_ATTEMPTS = 3
LOG_LOCK = threading.Lock()
STATE_PATH = os.path.join(TARGET, ".dsh_download_state.json")
os.makedirs(TARGET, exist_ok=True)
def log(msg):
with LOG_LOCK:
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
def http_json(url):
req = urllib.request.Request(url, headers={"User-Agent": "dsh"})
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r)
def head_size(url):
req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "dsh"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
cl = r.headers.get("Content-Length") or r.headers.get("x-linked-size")
if cl:
return int(cl)
except Exception as exc: # noqa: BLE001
log(f"HEAD failed for {url}: {exc}")
return None
def fetch_manifest():
url = f"{ENDPOINT}/{REPO}/resolve/main/MANIFEST.sha256"
try:
with urllib.request.urlopen(
urllib.request.Request(url, headers={"User-Agent": "dsh"}), timeout=30
) as r:
text = r.read().decode("utf-8", "replace")
except Exception as exc: # noqa: BLE001
log(f"manifest unavailable: {exc}")
return {}
out = {}
for line in text.splitlines():
parts = line.split()
if len(parts) == 2 and len(parts[0]) == 64:
out[parts[1]] = parts[0]
return out
def load_state():
if os.path.exists(STATE_PATH):
try:
with open(STATE_PATH, "r", encoding="utf-8") as fh:
return json.load(fh)
except Exception: # noqa: BLE001
pass
return {"files": {}}
def save_state(state):
tmp = STATE_PATH + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(state, fh, indent=1)
os.replace(tmp, STATE_PATH)
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as fh:
while True:
b = fh.read(4 * 1024 * 1024)
if not b:
break
h.update(b)
return h.hexdigest()
def download_chunk(url, start, end, fname, progress, key, state, state_lock, total_size):
"""Download [start, end] inclusive using this thread's own file handle."""
span = end - start + 1
attempt = 0
while True:
cur = progress["done"].get(key, 0)
if cur >= span:
return
attempt += 1
if attempt > MAX_RETRIES:
raise RuntimeError(f"gave up on {key} after {MAX_RETRIES} attempts")
try:
req = urllib.request.Request(url, headers={"User-Agent": "dsh"})
req.add_header("Range", f"bytes={start + cur}-{end}")
with urllib.request.urlopen(req, timeout=READ_TIMEOUT) as resp:
if resp.status == 206:
cr = resp.headers.get("Content-Range", "")
if not cr.startswith(f"bytes {start + cur}-"):
raise RuntimeError(f"unexpected Content-Range '{cr}' (wanted from {start + cur})")
elif resp.status == 200:
if start + cur != 0 or span < total_size:
raise RuntimeError("server ignored Range header")
else:
raise RuntimeError(f"HTTP {resp.status}")
with open(fname, "r+b", buffering=0) as fh:
fh.seek(start + cur)
win_start, win_bytes = time.time(), 0
while True:
buf = resp.read(256 * 1024)
if not buf:
break
fh.write(buf)
cur += len(buf)
win_bytes += len(buf)
progress["done"][key] = cur
with state_lock:
state["files"][progress["name"]]["done"][key] = cur
now = time.time()
if now - win_start >= STALL_WINDOW:
rate = win_bytes / (now - win_start)
if rate < STALL_MIN_RATE:
raise RuntimeError(
f"stalled at {rate / 1024:.0f} KB/s - reconnecting for a fresh burst"
)
win_start, win_bytes = now, 0
if cur >= span:
break
except Exception as exc: # noqa: BLE001
wait = min(60, 4 + 2 * attempt)
log(f" ! {progress['name']} chunk {key} attempt {attempt}: {exc} -> retry in {wait}s")
time.sleep(wait)
continue
if cur >= span:
return
def download_file(url, name, size, state, state_lock, expect_sha):
fname = os.path.join(TARGET, name)
os.makedirs(os.path.dirname(fname), exist_ok=True)
entry = state["files"].setdefault(name, {"size": size, "done": {}})
nchunks = max(1, min(WORKERS_PER_FILE, (size + CHUNK_MIN - 1) // CHUNK_MIN))
step = size // nchunks
ranges = []
for i in range(nchunks):
start = i * step
end = size - 1 if i == nchunks - 1 else (start + step - 1)
ranges.append((i, start, end))
if entry.get("size") != size:
entry["size"] = size
entry["done"] = {}
entry["done"] = {k: v for k, v in entry["done"].items() if k in {str(i) for i, _, _ in ranges}}
# preallocate WITHOUT zeroing what is already downloaded (resume-safe)
if not os.path.exists(fname):
with open(fname, "ab") as fh:
fh.truncate(size)
else:
have = os.path.getsize(fname)
if have > size:
os.truncate(fname, size)
elif have < size:
with open(fname, "ab") as fh:
fh.truncate(size)
progress = {"name": name, "done": {str(i): entry["done"].get(str(i), 0) for i, _, _ in ranges}}
threads = []
for i, start, end in ranges:
t = threading.Thread(
target=download_chunk,
args=(url, start, end, fname, progress, str(i), state, state_lock, size),
daemon=True,
)
t.start()
threads.append(t)
for t in threads:
t.join()
got = os.path.getsize(fname)
if got != size:
raise RuntimeError(f"{name}: size {got} != expected {size}")
if expect_sha:
digest = sha256_file(fname)
if digest != expect_sha:
raise RuntimeError(f"{name}: sha256 {digest[:12]}... != expected {expect_sha[:12]}...")
with state_lock:
entry["complete"] = True
log(f"downloaded + verified {name} ({size / 1048576:.1f} MB)")
return True
def download_simple(url, name, expect_sha):
fname = os.path.join(TARGET, name)
os.makedirs(os.path.dirname(fname), exist_ok=True)
part = fname + ".part"
for attempt in range(1, MAX_RETRIES + 1):
try:
req = urllib.request.Request(url, headers={"User-Agent": "dsh"})
with urllib.request.urlopen(req, timeout=READ_TIMEOUT) as resp, open(part, "wb") as fh:
while True:
buf = resp.read(256 * 1024)
if not buf:
break
fh.write(buf)
if expect_sha and sha256_file(part) != expect_sha:
raise RuntimeError("sha256 mismatch after download")
os.replace(part, fname)
log(f"downloaded + verified {name} ({os.path.getsize(fname) / 1024:.1f} KB)")
return True
except Exception as exc: # noqa: BLE001
wait = min(30, 2 + attempt)
log(f" ! {name} attempt {attempt}: {exc} -> retry in {wait}s")
time.sleep(wait)
raise RuntimeError(f"gave up on {name}")
def main():
log(f"endpoint {ENDPOINT} repo {REPO}")
log(f"target {TARGET}")
info = http_json(f"{ENDPOINT}/api/models/{REPO}?blobs=true")
manifest = fetch_manifest()
state = load_state()
state.setdefault("files", {})
state_lock = threading.Lock()
files = [s for s in info["siblings"] if s["rfilename"] != ".gitattributes"]
todo, simple, skipped = [], [], 0
for s in files:
name = s["rfilename"]
url = f"{ENDPOINT}/{REPO}/resolve/main/{name}"
path = os.path.join(TARGET, name)
want = manifest.get(name)
if want and os.path.exists(path) and os.path.getsize(path) == s["size"]:
if sha256_file(path) == want:
skipped += 1
log(f"already verified: {name}")
continue
size = s.get("size") or head_size(url)
if size:
todo.append((name, url, size, want))
else:
simple.append((name, url, want))
total = sum(s for _, _, s, _ in todo)
log(f"{len(todo)} chunked + {len(simple)} streamed file(s) to fetch, "
f"{total / 1048576:.1f} MB; {skipped} already good")
stop_saver = threading.Event()
def saver():
t0 = time.time()
last = 0
while not stop_saver.wait(5):
with state_lock:
save_state(state)
done = sum(sum(f.get("done", {}).values()) for f in state["files"].values())
if time.time() - t0 >= 20:
rate = (done - last) / (time.time() - t0)
pct = 100.0 * done / total if total else 100.0
eta = (total - done) / rate / 60 if rate > 0 else 0
log(f"progress {done / 1048576:.1f}/{total / 1048576:.1f} MB "
f"({pct:.1f}%) {rate / 1048576:.2f} MB/s eta {eta:.1f} min")
t0, last = time.time(), done
threading.Thread(target=saver, daemon=True).start()
failures = []
if todo or simple:
todo.sort(key=lambda x: -x[2])
for attempt in range(1, FILE_ATTEMPTS + 1):
with ThreadPoolExecutor(max_workers=MAX_FILES_PARALLEL) as pool:
futs = [
(name, pool.submit(download_file, url, name, size, state, state_lock, want))
for name, url, size, want in todo
]
futs += [
(name, pool.submit(download_simple, url, name, want))
for name, url, want in simple
]
failures = []
for name, fut in futs:
try:
fut.result()
except Exception as exc: # noqa: BLE001
log(f"FAILED {name}: {exc}")
failures.append((name, url, size if size else 0, want))
if not failures:
break
log(f"retrying {len(failures)} failed file(s), attempt {attempt}/{FILE_ATTEMPTS}")
todo, simple = [], []
for name, url, size, want in failures:
state["files"].pop(name, None)
todo.append((name, url, size, want))
save_state(state)
stop_saver.set()
save_state(state)
log("final sha256 verification ...")
bad = []
for name, want in sorted(manifest.items()):
path = os.path.join(TARGET, name)
if not os.path.exists(path):
log(f" MISSING {name}")
bad.append(name)
continue
ok = os.path.getsize(path) == next(
(s["size"] for s in files if s["rfilename"] == name), os.path.getsize(path)
) and sha256_file(path) == want
log(f" {'OK ' if ok else 'FAIL'} {name}")
if not ok:
bad.append(name)
if bad:
log(f"UNVERIFIED: {bad}")
return 1
log("ALL FILES VERIFIED OK")
for junk in (".dsh_download_state.json",):
p = os.path.join(TARGET, junk)
if os.path.exists(p):
os.remove(p)
return 0
if __name__ == "__main__":
sys.exit(main())
本文由 DSH Agent 记录 · 所有时间戳为北京时间(2026-10-10),取自下载器原始日志
posted on 2026-10-10 16:25 fox_charon 阅读(37) 评论(0) 收藏 举报
浙公网安备 33010602011771号