Git 与实验复现:保留实际运行的版本
Git and reproducibility
运行一次性 Git 实验,区分提交快照、暂存改动、被忽略数据与可重建证据。
git-reproducibility“同一提交”没有得到同一结果
同事给出一个结果和对应的 Git 提交。你检出该提交,运行命令,却得到另一个数字。两个人都未必算错:一人可能运行了尚未暂存的配置,另一人可能使用了被 Git 忽略的另一份数据。
Git 保存选定的项目快照。实验还依赖实际输入字节、配置、运行环境和执行选择。本章在一次性仓库中展示这种区别:同一个配置同时存在三个版本;稍后只改数据,结果就变了,git status 却仍然干净。
计算刻意保持简单:将两个观测的和乘以配置中的系数。没有训练模型或随机优化器,以免遮住真正变化的依赖。
提交只是实验记录的一部分
工作区、暂存区、提交是三份状态
工作区是普通程序读取的文件;索引也叫暂存区,保存为下次提交准备的版本。本例中,HEAD 指向当前提交。git add 后再编辑文件,不会自动更新已暂存版本;不带其他选项的 git commit 记录索引。Pro Git 第二版解释了这些快照概念。
系数依次经历以下状态:
| 时刻 | HEAD | 索引 | 工作区 | 对 [2,3] 的计算结果 |
|---|---|---|---|---|
| 初始提交 | 1 | 1 | 1 | 5 |
| 暂存 2,再编辑为 3 | 1 | 2 | 3 | 15 |
| 提交索引 | 2 | 2 | 3 | 15 |
| 从索引恢复工作文件 | 2 | 2 | 2 | 10 |
git diff 比较工作区与索引;git diff --cached 默认比较索引与 HEAD。重建未提交状态下的运行时,两份差异都重要。写在指标旁边的提交 ID,不会自动包含它们。Git diff 参考
干净状态有明确范围
对普通已跟踪路径,status 区分索引变化和工作区变化。程序请求稳定的 porcelain 版本 1、以 NUL 分隔的路径,并显示全部未跟踪文件。MM config.json 表示索引不同于 HEAD,工作文件又不同于索引;?? note.txt 表示未跟踪。本例没有冲突、重命名或子模块。Git status 参考
被忽略的未跟踪文件通常不会出现。.gitignore 不会归档该文件,也不会让 Git 停止跟踪已经入库的文件。这里故意排除 observations.json,代表单独管理的数据;状态干净,并不说明它的字节没有变化。Git ignore 参考
记录依赖边界
对本例的确定性计算,结果依赖执行的源码、配置和观测:
实验报告记录提交、状态、这三个文件的 SHA-256、结果,以及实际 Python 和 Git 版本。文件哈希标识记录器看到的字节,不会保存这些字节,也不证明其来源;产物仍须保留在能够取得的位置。Git 提交 ID 与单独计算的 SHA-256 文件指纹是不同标识。
本例展示以下推断不成立:
也就是:提交相同且状态干净,并不推出输入字节或结果相同。训练流水线还应记录预处理、划分 ID、超参数、种子及相关环境细节。种子在指定条件下约束随机流,却不能固定数据集、库实现或非确定性的硬件执行。
运行失败例,再重建结果
完整程序需要 Python 3.12 和可执行的 Git。它创建一个临时仓库,不配置远程,只运行自己写出的短 Python 计算,最后删除该仓库。Git 设置与示例作者身份传给子进程,并排除全局/系统配置及继承的 Git 覆盖变量。空模板与空 hook 目录让演示不依赖用户 hook,不修改现有仓库或全局配置。
固定作者日期让演示提交更少变化,不表示真实实验发生于该日。仓库显式采用 SHA-1 Git 对象;程序使用的 SHA-256 文件指纹不受这一选择影响。
from pathlib import Path
from tempfile import TemporaryDirectory
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
RUNNER = '''from pathlib import Path
import json
config = json.loads(Path('config.json').read_text())
data = json.loads(Path('observations.json').read_text())
print(config['factor'] * sum(data))
'''
def encode(value):
return (json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n').encode()
def digest(data):
return hashlib.sha256(data).hexdigest()
def experiment():
executable = shutil.which('git')
if executable is None:
raise RuntimeError('Git must be installed and available on PATH')
env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_')}
env.update(GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull,
GIT_TERMINAL_PROMPT='0', LC_ALL='C',
GIT_AUTHOR_DATE='2026-01-01T00:00:00+00:00',
GIT_COMMITTER_DATE='2026-01-01T00:00:00+00:00')
with TemporaryDirectory(prefix='aiwiki-git-example-') as name:
root = Path(name)
repo = root / 'repo'
template = root / 'empty-template'
template.mkdir()
options = [executable, '-c', 'user.name=AI Wiki Example',
'-c', 'user.email=example@example.invalid',
'-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false',
'-c', 'core.excludesFile=' + os.devnull,
'-c', 'core.hooksPath=' + str(template)]
def git(*args):
return subprocess.run(options + ['-C', str(repo), *args],
env=env, check=True, capture_output=True).stdout
subprocess.run(options + ['init', '--quiet', '--initial-branch=main',
'--object-format=sha1', '--template=' + str(template),
str(repo)], env=env, check=True, capture_output=True)
(repo / 'run.py').write_text(RUNNER)
(repo / '.gitignore').write_text('/observations.json\n')
(repo / 'config.json').write_bytes(encode({'factor': 1}))
data = encode([2, 3])
(repo / 'observations.json').write_bytes(data)
git('add', '--', 'run.py', '.gitignore', 'config.json')
git('commit', '--quiet', '-m', 'Record calculation and configuration')
def record():
names = ('run.py', 'config.json', 'observations.json')
before = {n: (repo / n).read_bytes() for n in names}
result = subprocess.run([sys.executable, '-I', '-B', 'run.py'],
cwd=repo, env=env, check=True, capture_output=True).stdout
after = {n: (repo / n).read_bytes() for n in names}
if before != after:
raise RuntimeError('inputs changed while the example ran')
return {'commit': git('rev-parse', 'HEAD').decode().strip(),
'status': git('status', '--porcelain=v1', '-z',
'--untracked-files=all').decode(),
'sha256': {n: digest(b) for n, b in before.items()},
'result': int(result), 'python': platform.python_version(),
'git': git('--version').decode().strip()}
baseline = record()
(repo / 'config.json').write_bytes(encode({'factor': 2}))
git('add', '--', 'config.json')
(repo / 'config.json').write_bytes(encode({'factor': 3}))
layers = {'head': json.loads(git('show', 'HEAD:config.json'))['factor'],
'index': json.loads(git('show', ':config.json'))['factor'],
'worktree': json.loads((repo / 'config.json').read_bytes())['factor'],
'staged_diff': git('diff', '--cached', '--', 'config.json').decode(),
'unstaged_diff': git('diff', '--', 'config.json').decode()}
staged = record()
git('commit', '--quiet', '-m', 'Commit the staged factor two')
committed = record()
committed_factor = json.loads(git('show', 'HEAD:config.json'))['factor']
# Only this disposable repository is restored.
git('restore', '--worktree', '--', 'config.json')
restored = record()
(repo / 'observations.json').write_bytes(encode([2, 4]))
changed_data = record()
ignored = git('check-ignore', '--', 'observations.json').decode().strip()
(repo / 'observations.json').write_bytes(data)
replayed = record()
(repo / 'note.txt').write_text('An untracked note.\n')
with_untracked = record()
return {'layers': layers, 'committed_factor': committed_factor,
'ignored': ignored, 'baseline': baseline, 'staged': staged,
'committed': committed, 'restored': restored,
'changed_data': changed_data, 'replayed': replayed,
'with_untracked': with_untracked}
def main():
r = experiment()
print('HEAD / index / worktree:', r['layers']['head'],
r['layers']['index'], r['layers']['worktree'])
print('staged status / run:', repr(r['staged']['status']), r['staged']['result'])
print('committed factor / worktree run:', r['committed_factor'], r['committed']['result'])
a, b = r['restored'], r['changed_data']
print('same commit / both clean:', a['commit'] == b['commit'],
a['status'] == b['status'] == '')
print('ignored-data results / hash changed:', a['result'], b['result'],
a['sha256']['observations.json'] != b['sha256']['observations.json'])
print('restored bytes / result:', r['replayed']['sha256'] == a['sha256'],
r['replayed']['result'])
print('untracked status:', repr(r['with_untracked']['status']))
if __name__ == '__main__':
main()
输出:
HEAD / index / worktree: 1 2 3
staged status / run: 'MM config.json\x00' 15
committed factor / worktree run: 2 15
same commit / both clean: True True
ignored-data results / hash changed: 10 12 True
restored bytes / result: True 10
untracked status: '?? note.txt\x00'
暂存系数 2、再编辑为 3 后,实际计算仍读取 3,得到 15;提交也不会替换工作文件。后面的 restore 只作用于这个临时仓库,将索引里的系数 2 复制到工作区,得到 10。
把被忽略的观测从 [2,3] 改为 [2,4],结果变成 12,提交和干净状态却相同;数据指纹变了。恢复保存的输入字节,又得到 10。最后,新建的未跟踪笔记会出现在状态里,尽管计算不读取它。状态不干净意味着要检查依赖,并不证明每个变化都影响结果。
record 比较执行前后的三个文件,可发现运行期间普通的持续修改,但不是原子文件系统快照:并发进程可能在两次读取之间修改又恢复文件。本演示没有并发写者,生产记录器需要不可变输入位置或更强的快照机制。
设三个记录文件共有 B 字节,哈希和前后字节快照需要 O(B) 工作与内存。这个简单计算的工作量与读取的观测数成正比。Git 状态、对象查询、提交的成本还受仓库规模和存储影响,本例不声称常数时间或吞吐量。返回报告是少数固定输入的证据,不是完整实验追踪服务。
重建需要的不只是指纹
报告范围只有三个文件与两个版本字符串,未冻结 Python 可执行文件、操作系统、间接依赖或外部服务。本整数例在本地重现,但 GPU 训练可能更适合带容差的检查,而非要求输出逐位一致。比较重跑之前,应先定义验收:输入身份相同、指标在规定容差内相同、科学结论相同,是不同要求。
Git 不负责制定数据保留策略。大型或受限产物可以保存在独立存储中,记录不可变标识和取得方法。哈希可以检查取回的产物;产物丢失时,无法从哈希重建。忽略文件也不会清除其过去已提交的版本。
共享实验宜对应已经记录并保留的提交,分支名会移动。探索性运行若使用未提交改动,应保存实际源码快照,或适用的暂存与未暂存补丁,同时记录依赖。本例的小记录器不覆盖任意未跟踪代码、重命名路径、子模块状态或文件权限。
临时例不含凭据或私人数据。它说明复现需要保留哪些证据,不意味着所有数据集或配置值都应进入仓库。
找出缺失的证据
- 读懂三个版本。系数 2 暂存后,工作文件又编辑为 3。普通提交保存哪个版本,程序运行哪个版本?
追踪两次读取
答案:提交保存暂存的系数 2,程序读取工作区系数 3,因此 [2,3] 得到 15。提交前可分别通过 git diff --cached 和 git diff 查看两份差异。
- 审查干净的运行。为什么例中同一干净提交可以分别得到 10 与 12?
看看已跟踪文件之外
答案:被忽略的观测从 [2,3] 改成 [2,4],已跟踪的系数 2 没变。独立输入哈希能区分这两次运行,普通干净状态不能。
- 恢复输入。报告保存了数据 SHA-256,但产物被删除,足够重跑吗?
标识不是存储
答案:不够。哈希可校验候选字节,却不提供字节本身。应保留产物,或保留带不可变来源版本的可复现获取过程,再用已记录指纹核对恢复出的字节。
- 解释变化的状态。最后一份报告出现
?? note.txt,结果仍为 10。未跟踪文件一定让计算失效吗?
检查依赖关系
答案:不会。这个计算从不读取笔记。状态揭示提交之外还有文件,应判断其影响,而不是悄悄忽略。如果它是程序会导入的未跟踪模块,就属于应保存的缺失依赖。
把版本控制连接到实验证据
Pro Git给出快照和暂存模型,diff、status及忽略规则参考进一步明确可观察边界。对 AI 实验而言,它们帮助确定保留了哪个源码版本,以及哪些差异仍在其外。
继续阅读环境与依赖管理,理解运行时隔离;阅读随机数与随机种子,理解随机执行。AI 数据工作的 SQL则说明,保留查询之后,还须记录源数据与信息时间边界。
先判断,再看解释
干净提交没变,但被忽略的数据文件变了,结果必须不变吗?
学习目标
- 区分执行的工作文件、暂存版本与提交快照。
- 解释为何干净状态与提交 ID 不能标识被忽略的输入数据。
- 将依赖指纹与可取得的产物、明确运行时范围一起保留。
先修与延伸
查看知识关联图 →参考文献
- Pro Git, second edition — What is Git?
Scott Chacon; Ben Straub - git-diff — Git 2.52.0 documentation
Git contributors - git-status — Git documentation
Git contributors - gitignore — Git 2.52.0 documentation
Git contributors
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Python 3.12.4、实际 Git 2.52.0 下 8 项测试通过。所有 Git 写操作及计算子进程仅在 TemporaryDirectory 仓库中执行,无远程;测试注入伪造的继承 GIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILE,检查子进程参数以验证覆盖变量移除、配置隔离及仅临时路径。两次测试临时仓库均已清理。
- 独立读取器解压松散 Git 对象,检查头部长度与 SHA-1 身份,解析二进制树条目并跟随父提交,不调用 git show 或 ls-tree;核对恰有两个已提交快照,系数依次 2、1,只含声明的三个跟踪文件,观测文件不在其中。字面字节 SHA-256 核对系数二配置和两版数据,不复用规范 JSON 编码器。
- 测试核对暂存/未暂存差异端点、七个真实结果、状态变化、HEAD 不变而工作状态变化、相同干净提交与不同忽略输入、精确重放报告、无关未跟踪笔记及 Git 缺失时明确失败。程序是固定确定性溯源实验,不是通用仓库记录器;明确执行前后输入比较不是原子快照。
- 原创完整双语含相同可执行 Python、七行输出、两对公式、六锚点、四已答练习,严格 MDX/KaTeX 及 React 实际 HTML 通过。固定示例提交日期不冒充真实历史事件;按 Humanizer 指南复读依赖保留、哈希/来源真实性范围、版本/种子限制及字节成本。保持 written,仅 AI 作者检查,不是人工或全站批准。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- Pro Git, second edition — What is Git? · Actually read official Pro Git second-edition chapter lines 190–206 for snapshots/local history and 220–245 for modified/staged/committed states, working tree, index and plain commit workflow. The old chapter SHA-1 wording is not generalized to all modern repositories; the demo explicitly requests SHA-1 objects and separately uses SHA-256 artifact fingerprints. No book diagrams, examples or code are copied.
- git-diff — Git 2.52.0 documentation · Actually read fixed Git 2.52.0 git-diff reference lines 285–310 and 1156–1170 for working tree versus index, --cached versus HEAD, and named commit comparisons. The two captured diffs are actually executed and checked at their independent endpoints. No unstaged-patch capture service is claimed.
- git-status — Git documentation · Actually read official git-status live page lines 259–278 for porcelain/untracked options, 438–461 for two-column states, and 485–493 for stable v1 and NUL path format. The attempted /2.52.0 and trailing-slash URLs returned only a three-line redirect document, so the source card is explicitly unversioned rather than pretending that version was read. Actual runtime is Git 2.52.0; the tiny example contains no conflicts, renames or submodules.
- gitignore — Git 2.52.0 documentation · Actually read fixed Git 2.52.0 gitignore reference lines 223–239 for deliberately untracked files, tracked-file exclusion from these rules, and ignore-file precedence. Demo uses an explicit .gitignore with global excludes disabled, actual check-ignore, and a separately fingerprinted input. No claim that ignore rules remove history or retain data.
- Pro Git, second edition — What is Git? · Actually read the official second-edition chapter on snapshots and local history, and The Three States (lines 220–245). Plain commit records the index. SHA-1 discussion is scoped to the explicitly selected demo object format.
- git-diff — Git 2.52.0 documentation · Actually read the fixed 2.52.0 reference, DESCRIPTION lines 285–310: default index/worktree, --cached HEAD/index and explicit commit comparisons.
- git-status — Git documentation · Actually read the live official reference, short format lines 390–461 and porcelain v1 lines 485–493: index/worktree columns, ignored/untracked scope and NUL termination. Runtime tested Git 2.52.0; source card correctly remains unversioned.
- gitignore — Git 2.52.0 documentation · Actually read fixed 2.52.0 DESCRIPTION lines 223–239: intentionally untracked files, already-tracked exception and precedence. Ignoring does not erase tracked history or retain input data.
相关主题