runner 教程
本教程构建逼真程度逐步提高的基准测试用例:单次比较、JSONL 事件流、具有显式生命周期的可变输入、有状态的操作序列、在计时之前被捕获并最小化的错误实现、每个规模多个随机数据集,以及你自己的协议。每个示例都是一个完整的 async test;展示的输出是不取决于你的机器速度的部分。
| 我想要 | 用法 |
|---|---|
| 在同一输入上比较多个实现 | @runner.Case::single_step(...).with_immutable_input(...).compare(...) |
| 先对照参考实现进行验证 | .against_equal(...),或用 BenchSpec::advanced 构建完整的判定器 |
| 保留原始记录 | RunContext 中的 @event.JsonlSink |
| 为可变输入提供生命周期 | 带有 prepare 和 reset 的 @fixture.Fixture |
| 测量有状态的操作序列 | 带有 Context 的 Implementation::in_process |
| 选择测量的仔细程度 | @runner.ProtocolPreset 或 @runner.validate_protocol |
| 在每个规模上测量多个数据集 | ExperimentDesign::HierarchicalDatasetsAndRepeats 或 MultipleDatasetsSingleMeasurement |
| 选择验证哪些内容 | 协议中的 ValidationCoverage |
| 隔离可能崩溃的负载 | Implementation::worker(native) |
快速上手
moon add Luna-Flow/mare_mark@0.4.2
import {
"Luna-Flow/mare_mark/model",
"Luna-Flow/mare_mark/env_detect",
"Luna-Flow/mare_mark/event",
"Luna-Flow/mare_mark/runner",
"moonbitlang/async",
"Luna-Flow/mare_mark/fixture",
"Luna-Flow/mare_mark/experiment",
"Luna-Flow/mare_mark/generator",
}
一次运行需要一个环境快照。让 env_detect 描述机器,并声明它无法知道的内容:代码是如何构建的,以及基准测试一次运行多少个操作。
async fn this_machine() -> @model.EnvironmentSnapshot {
@env_detect.detect(compiler_flags="release", dtype_abi="i64", concurrency=1).snapshot
}
快照还会得到一个新的来源信息运行 id,因此本教程的每次运行都有自己的 RunSummary.run_id。如果想手工描述机器,请用 @model 构造函数构建快照(参见 model 教程)。
然后比较两种对 0, 1, …, n-1 求和的方法:
async test "quick start" {
let looped = @runner.Implementation::stateless("loop", "1", (n : Int) => {
let mut total = 0
for i in 0..<n {
total += i
}
@model.OperationResult::completed(total, ())
})
let closed = @runner.Implementation::stateless("formula", "1", (n : Int) => {
@model.OperationResult::completed(n * (n - 1) / 2, ())
})
let plan = @runner.single_step("triangle", [100, 10000])
.with_immutable_input(context => context.dataset_key.scale, n => n.to_string())
.compare([looped, closed])
.against_equal(n => n * (n - 1) / 2, (expected, actual) => expected == actual)
.compile()
.unwrap()
let memory = @event.InMemorySink::new()
let context = @runner.RunContext::new(
this_machine(), memory.as_sink(), 42UL, @runner.ProtocolPreset::QuickCheck.validated(),
)
let summary = @runner.run(plan, context)
inspect(summary.passed_count, content="4")
inspect(memory.observations.length(), content="16")
inspect(memory.calibrations.length(), content="4")
}
两个实现在两个规模上都通过了验证(四次验证)。随后每个规模为每个实现进行了一次校准,并运行了四个区组(QuickCheck:一个探索性、三个验证性),每个区组包含两个批次。memory.observations[i].raw_elapsed_us 保存了每次迭代的时间。
日常任务
把运行保存为 JSONL
JSONL 流是一次运行的审计记录。把事件发送到 JsonlSink,并用 tee 同时发送到内存:
async test "write JSONL and keep events in memory" {
let id = @runner.Implementation::stateless("identity", "1", (x : Int) => {
@model.OperationResult::completed(x, ())
})
let plan = @runner.single_step("identity", [1])
.with_immutable_input(context => context.dataset_key.scale, x => x.to_string())
.compare([id])
.against_equal(x => x, (expected, actual) => expected == actual)
.compile()
.unwrap()
let jsonl = @event.JsonlSink::new()
let memory = @event.InMemorySink::new()
let sink = @event.tee(memory.as_sink(), jsonl.as_sink())
let summary = @runner.run(
plan,
@runner.RunContext::new(this_machine(), sink, 7UL, @runner.ProtocolPreset::QuickCheck.validated()),
)
let location = summary.artifact_location.unwrap()
inspect(location.has_prefix("jsonl://memory/identity|mmkp_2:a8272a0d9e84b872|7|"), content="true")
let lines = jsonl.to_jsonl().split("\n").to_array()
inspect(lines.length(), content="7")
inspect(lines[0].contains("\"type\":\"validation\""), content="true")
inspect(lines[6].contains("\"type\":\"summary\""), content="true")
}
一次验证、一次校准、四个观测和摘要,共七行。位置以运行 id 结尾:用例、协议标识、种子,以及检测到的环境的来源信息运行 id 和时间戳。用你自己的 IO 把 jsonl.to_jsonl() 写入文件,或者用 @event.streaming_jsonl 在事件发生时逐行流式写出。
为可变输入提供显式的生命周期
原地排序会破坏它的输入。夹具在每个批次之前复制生成的数组(PerBatch),并把这次复制放在计时区域之外(ExcludedFromMeasurement):
async test "an in-place sort on a fresh copy per batch" {
let fixture : @fixture.Fixture[Int, Array[Int], Array[Int]] = @fixture.Fixture::new(
"descending",
"1",
context => Array::makei(context.dataset_key.scale, i => context.dataset_key.scale - i),
input => "len=" + input.length().to_string(),
input => input.copy(),
(input, _, _) => input,
(_, _) => (),
@model.SetupPolicy::new(
@model.SetupFrequency::PerBatch,
@model.SetupTiming::ExcludedFromMeasurement,
@model.WorkspaceScope::BatchWorkspace,
),
)
let sort_in_place = @runner.Implementation::stateless("sort", "1", (xs : Array[Int]) => {
xs.sort()
@model.OperationResult::completed(xs[0], ())
})
let oracle = @experiment.ReferenceOracle::equal(
"minimum",
(input : Array[Int]) => input.fold(init=input[0], (low, x) => if x < low { x } else { low }),
(expected, actual) => expected == actual,
)
let spec = @runner.BenchSpec::advanced(
"sort",
fixture,
[sort_in_place],
@runner.OutputSink::keep_last(),
@experiment.OracleSpec::Reference(oracle),
[64, 4096],
n => n.to_string(),
1,
(input, _) => @model.CaseDescriptor::new("sort", [input.length().to_string()], "", ""),
input => "len=" + input.length().to_string(),
first => first.to_string(),
_ => "",
(input, implementation) => @model.ReplaySpec::new("sort-worker", [implementation, input.length().to_string()]),
)
let memory = @event.InMemorySink::new()
let summary = @runner.run(
spec.compile().unwrap(),
@runner.RunContext::new(this_machine(), memory.as_sink(), 1UL, @runner.ProtocolPreset::QuickCheck.validated()),
)
inspect(summary.passed_count, content="2")
inspect(memory.observations.all(o => o.valid), content="true")
}
如果没有 clone_input,第二个批次就会对一个已经排好序的数组排序,测量的是另一种工作负载。要把复制计入测量,请使用 IncludedInMeasurement;要在每一次操作之前都复制,请使用 PerIteration。runner 设计精确列出了每种组合会把哪些内容放进时钟之内。
验证有状态的序列
携带状态的操作(例如累计总和)作为序列进行验证。实现和参考判定器各自传递自己的上下文,sequence_length 设定比较多少步:
async test "a running total validated over five steps" {
let fixture : @fixture.Fixture[Int, Int, Int] = @fixture.Fixture::immutable(
"step",
"1",
context => context.dataset_key.scale,
x => x.to_string(),
)
let running = @runner.Implementation::in_process("running", "1", () => 0, (step : Int, total : Int) => {
@model.OperationResult::completed(total + step, total + step)
})
let reference = @experiment.ReferenceOracle::new(
"running-total",
() => 0,
_ => 5,
(step : Int, index, total : Int) => {
ignore(index)
@model.OperationResult::completed(total + step, total + step)
},
(_, _, expected, actual) => {
match (expected, actual) {
(Value(e), Value(a)) if e == a => @model.ValidationStatus::Valid
_ => @model.ValidationStatus::Invalid("total differs")
}
},
total => total.to_string(),
)
let spec = @runner.BenchSpec::advanced(
"running-total",
fixture,
[running],
@runner.OutputSink::new(() => 0, (sum, x) => sum + x, sum => sum),
@experiment.OracleSpec::Reference(reference),
[3],
n => n.to_string(),
5,
(step, index) => @model.CaseDescriptor::new("add", [step.to_string(), index.to_string()], "total", ""),
x => x.to_string(),
x => x.to_string(),
total => total.to_string(),
(step, implementation) => @model.ReplaySpec::new("total-worker", [implementation, step.to_string()]),
)
let memory = @event.InMemorySink::new()
let summary = @runner.run(
spec.compile().unwrap(),
@runner.RunContext::new(this_machine(), memory.as_sink(), 3UL, @runner.ProtocolPreset::QuickCheck.validated()),
)
inspect(summary.validation_count, content="5")
inspect(summary.passed_count, content="5")
guard memory.validations[4].evidence is Some(evidence) else { fail("no evidence") }
inspect(evidence.actual, content="15")
inspect(evidence.context, content="15")
}
序列的第 4 步返回 ,证据同时记录了该值和该步之后的上下文。
对于参考判定器,sequence_length(input) 必须返回一个正值,且等于上文所示的用例长度。运行器会将该值用于两个序列。若长度不一致,会抛出 RunConfigError;若实现或判定器在通过若干步骤后提前停止,则会明确生成一条长度不匹配的无效结果。这样,共有前缀就不会被误认为是完整检查。
捕获并最小化错误的实现
一个差一错误的实现没有通过验证。有了缩减器,运行器会在写出失败产物之前缩小失败的输入:
async test "a failing implementation is minimized" {
let off_by_one = @runner.Implementation::stateless("off-by-one", "0.1", (x : Int) => {
@model.OperationResult::completed(x + 1, ())
})
let spec = @runner.BenchSpec::advanced(
"identity",
@fixture.Fixture::immutable("ints", "1", context => context.dataset_key.scale, (x : Int) => x.to_string()),
[off_by_one],
@runner.OutputSink::keep_last(),
@experiment.OracleSpec::Reference(
@experiment.ReferenceOracle::equal("identity", x => x, (expected, actual) => expected == actual),
),
[40],
n => n.to_string(),
1,
(x, _) => @model.CaseDescriptor::new("identity", [x.to_string()], "", ""),
x => x.to_string(),
x => x.to_string(),
_ => "",
(x, implementation) => @model.ReplaySpec::new("identity-worker", [implementation, x.to_string()]),
shrinker=@experiment.Shrinker::new(x => if x > 0 { [x / 2] } else { [] }, x => x.to_string()),
)
let memory = @event.InMemorySink::new()
let summary = @runner.run(
spec.compile().unwrap(),
@runner.RunContext::new(this_machine(), memory.as_sink(), 9UL, @runner.ProtocolPreset::QuickCheck.validated()),
)
inspect(summary.failed_count, content="1")
let failure = memory.failures[0]
inspect(failure.minimal_input, content="0")
debug_inspect(failure.shrink_path, content="[\"20\", \"10\", \"5\", \"2\", \"1\", \"0\"]")
}
失败事件携带种子、原始指纹和最小指纹、缩减路径以及重放命令 identity-worker off-by-one 40。该实现仍会被计时;报告会隐藏它的系列,改为显示不匹配。
在每个规模上测量多个随机数据集
每个规模一个固定数据集可以非常精确地测量一个输入;但结果仍可能取决于那个特定的输入。使用随机输入时,请在每个规模上测量多个数据集。HierarchicalDatasetsAndRepeats 每隔 repeats_per_dataset 个连续区组提供一个新数据集,因此运行能看到多个输入,同时仍会重复测量每个输入。生成器必须利用数据集:对每个数据集,GenerationContext.seed 都是运行种子,而 dataset_key.dataset_id 用来区分它们。
fn random_values(seed : UInt64, length : Int) -> Array[Int] {
let mut state = seed
Array::makei(length, _ => {
state = state * 6364136223846793005UL + 1442695040888963407UL
(state >> 33).to_int() % 1000
})
}
async test "four datasets per scale, two blocks each" {
let fixture : @fixture.Fixture[Int, Array[Int], Array[Int]] = @fixture.Fixture::immutable(
"random-values",
"1",
context => {
let seed = @generator.derive_seed(context.seed, context.case_id, context.dataset_key.dataset_id)
random_values(seed, context.dataset_key.scale)
},
xs => xs.length().to_string() + ":" + xs.fold(init=0, (hash, x) => hash * 31 + x).to_string(),
)
let looped = @runner.Implementation::stateless("loop", "1", (xs : Array[Int]) => {
let mut total = 0
for x in xs {
total += x
}
@model.OperationResult::completed(total, ())
})
let folded = @runner.Implementation::stateless("fold", "1", (xs : Array[Int]) => {
@model.OperationResult::completed(xs.fold(init=0, (total, x) => total + x), ())
})
let spec = @runner.BenchSpec::advanced(
"sum",
fixture,
[looped, folded],
@runner.OutputSink::keep_last(),
@experiment.OracleSpec::Reference(
@experiment.ReferenceOracle::equal("sum", xs => xs.fold(init=0, (total, x) => total + x), (expected, actual) => expected == actual),
),
[100, 1000],
n => n.to_string(),
1,
(xs, _) => @model.CaseDescriptor::new("sum", [xs.length().to_string()], "", ""),
xs => xs.length().to_string(),
total => total.to_string(),
_ => "",
(xs, implementation) => @model.ReplaySpec::new("sum-worker", [implementation, xs.length().to_string()]),
)
let protocol = @runner.validate_protocol(
@model.RunProtocol::new(
@model.ExperimentDesign::HierarchicalDatasetsAndRepeats,
1,
None,
@model.CalibrationProtocol::new(1000.0, 1, 1000, 100000.0, @model.BatchPolicy::PerImplementation),
1.0,
@model.OrderPolicy::BalancedBlocks(1UL),
@model.OutlierPolicy::ReportOnly,
@model.ValidationCoverage::ConfirmatoryOnly,
2,
6,
repeats_per_dataset=2,
),
).unwrap()
let memory = @event.InMemorySink::new()
let summary = @runner.run(
spec.compile(protocol~).unwrap(),
@runner.RunContext::new(this_machine(), memory.as_sink(), 7UL, protocol),
)
inspect(summary.observation_count, content="32")
inspect(summary.validation_count, content="12")
let datasets = memory.observations
.filter(o => o.implementation_id == "loop" && o.scale_text == "1000")
.map(o => (o.block_id, o.dataset_id))
debug_inspect(datasets, content="[(0, 4), (1, 4), (2, 5), (3, 5), (4, 6), (5, 6), (6, 7), (7, 7)]")
inspect(memory.validations.all(v => v.measurement is None), content="true")
}
每个规模有 个区组和 个数据集,因此两个规模和两个实现给出 32 个观测。一个规模的区组 测量索引为 的数据集;id 跨规模连续编号(规模 1000 的数据集为 4 到 7)。每个规模的第一个数据集只由两个探索性区组测量,预热和校准也在它上面运行。ConfirmatoryOnly 验证由验证性区组测量的三个数据集:3 个数据集、2 个规模、2 个实现、每次一步,共 12 次验证。validate_protocol 要求 2 整除两个样本数,因此没有数据集横跨两个阶段。
协议的其他选择也以同样的方式工作:
| 目的 | 设置 |
|---|---|
| 每个区组测量一个数据集 | MultipleDatasetsSingleMeasurement(并且 repeats_per_dataset 为 1) |
| 验证每个数据集,包括探索性数据集 | ValidationCoverage::EveryDataset |
| 还要在每个被测批次之前立即验证 | ValidationCoverage::EveryMeasurement(验证携带批次的 MeasurementKey) |
无论覆盖方式如何,验证从不在计时区域内运行;更多的覆盖消耗的是挂钟时间,而不是准确度。
编写你自己的协议
预设涵盖了常见情形。对于 CI 中的门禁,你可能需要更多的验证性区组,并取实现数量的倍数,使每个轮换周期都完整:
test "a custom protocol" {
let protocol = @model.RunProtocol::new(
@model.ExperimentDesign::FixedDatasetRepeatedMeasurements,
5,
Some(20000.0),
@model.CalibrationProtocol::new(2000.0, 4, 100000, 200000.0, @model.BatchPolicy::PerImplementation),
2.0,
@model.OrderPolicy::BalancedBlocks(2026UL),
@model.OutlierPolicy::ReportOnly,
@model.ValidationCoverage::EveryDataset,
2,
30,
)
let validated = @runner.validate_protocol(protocol).unwrap()
let preset = @runner.ProtocolPreset::Custom(validated)
inspect(preset.validated().protocol.confirmatory_samples, content="30")
inspect(@model.protocol_identity(protocol), content="mmkp_2:099f165751bb177e")
}
有两个实现时, 个区组构成 16 个完整周期。该标识是每个字段的摘要;改变其中任何一个,即使是顺序种子,也会得到另一个标识。
更进一步
隔离不安全的代码。 Implementation::worker 在带超时的子进程中运行每次操作;崩溃会变成 Aborted 结果,挂起会变成 Timeout,两者都计为基础设施失败。工作者需要 native 目标。参见 WorkerSpec。
异步设备。 向 Implementation::in_process 传入 synchronize=,其函数会阻塞直到排队的工作完成。运行器会在启动时钟之前和停止时钟之前立即调用它。
每批次相等的工作量。 BatchPolicy::SharedBatchSize 为每个实现提供校准得到的最小批次大小。
多个实现相互比较。 当不存在唯一参考时,使用 OracleSpec::Relational 或 ReferenceAndRelational 对实现进行两两比较;参见 experiment 教程。
可复现的输入。 在夹具中用 @generator.derive_seed(context.seed, context.case_id, context.dataset_key.dataset_id) 派生数据集种子;参见 generator 教程。
常见陷阱
- 负载内部不属于负载的工作。 实现函数内部的分配、解析或打印都会被计时。请把它们移到夹具中。
- 对会修改数据的代码忘记
clone_input。 这样之后的批次测量的是另一个输入。 - 从无效观测中读取计时。 比较之前请按
valid过滤,并丢弃有验证失败的数据集。 - 混合不同阶段。 探索性区组用于摸底;请基于验证性区组做决策。
- 复用来源信息中的运行 id。
RunSummary.run_id由用例、协议标识、种子以及来源信息中的运行 id 和时间戳构建;每次运行都复用同一个手写快照,会使一个用例的每次运行都得到相同的 id。@env_detect.detect每次都会生成一个新的来源信息运行 id。 - 每个数据集中的输入都相同。 在
MultipleDatasetsSingleMeasurement和HierarchicalDatasetsAndRepeats下,夹具对每个数据集以相同的运行种子调用一次;请根据dataset_key.dataset_id派生输入,否则每个数据集都是相同的。 - 在多个数据集上使用
PerRun准备。 全运行范围的准备值只能来自一个数据集,因此compile和run会拒绝它;请使用PerDataset。 - 在异步上下文之外调用
run。 它是一个async fn。 - 在有噪声的数据上使用零阈值。
validate_protocol接受0.0,此时stats.compare_paired会把每个非零差异都判为Faster或Slower。请选择你关心的最小变化。
后续步骤
- runner API 和 runner 设计。
- stats 教程:把观测转化为决策。
- report 教程:把 JSONL 发布为 HTML。
- fixture 教程和 experiment 教程:生命周期与判定器。