repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
locust
examples/terraform/aws/plan/basic.py
.py
from locust import HttpUser, between, task class Quickstart(HttpUser): wait_time = between(1, 5) @task def google(self): self.client.request_name = "google" self.client.get("https://google.com/") @task def microsoft(self): self.client.request_name = "microsoft" se...
21
490
locust
examples/dispatch_test_scripts/locustfile.py
.py
from locust import HttpUser, LoadTestShape, constant, task class UserA(HttpUser): wait_time = constant(600) # host = "https://example.com" @task def get_root(self): self.client.get("/", name="UserA") class UserB(HttpUser): wait_time = constant(600) # host = "https://example.com" ...
79
2,097
locust
examples/milvus/locustfile.py
.py
""" Minimal example demonstrating Milvus load testing with Locust. """ from locust import between, task from locust.contrib.milvus import MilvusUser import random from pymilvus import CollectionSchema, DataType, FieldSchema from pymilvus.milvus_client import IndexParams class SimpleMilvusUser(MilvusUser): """M...
83
2,422
locust
examples/mongodb/locustfile.py
.py
from locust import task from locust.contrib.mongodb import MongoDBUser import os class MongoUser(MongoDBUser): conn_string = os.getenv("MONGODB_URI", "mongodb://localhost:27017/defaultdb") db_name = "test" # change to your db name @task def db_query(self): self.client.execute_query("collect...
14
399
locust
examples/qdrant/locustfile.py
.py
""" Minimal example demonstrating Qdrant load testing with Locust. """ from locust import between, task from locust.contrib.qdrant import QdrantUser import random from qdrant_client.models import Distance, PointStruct, VectorParams class SimpleQdrantUser(QdrantUser): """Minimal Qdrant user for load testing."""...
56
1,435
locust
examples/custom_shape/staging_user_classes.py
.py
from locust import HttpUser, LoadTestShape, TaskSet, constant, task class UserTasks(TaskSet): @task def get_root(self): self.client.get("/") class WebsiteUserA(HttpUser): wait_time = constant(0.5) tasks = [UserTasks] class WebsiteUserB(HttpUser): wait_time = constant(0.5) tasks = [...
58
1,895
locust
examples/custom_shape/wait_user_count.py
.py
from locust import HttpUser, LoadTestShape, TaskSet, constant, task import random import time from collections import namedtuple class UserTasks(TaskSet): @task def get_root(self): self.client.get("/") class WebsiteUser(HttpUser): wait_time = constant(0.5) tasks = [UserTasks] def __ini...
73
2,238
locust
examples/custom_shape/double_wave.py
.py
from locust import HttpUser, LoadTestShape, TaskSet, constant, task import math class UserTasks(TaskSet): @task def get_root(self): self.client.get("/") class WebsiteUser(HttpUser): wait_time = constant(0.5) tasks = [UserTasks] class DoubleWave(LoadTestShape): """ A shape to imita...
49
1,339
locust
examples/custom_shape/stages.py
.py
from locust import HttpUser, LoadTestShape, TaskSet, constant, task class UserTasks(TaskSet): @task def get_root(self): self.client.get("/") class WebsiteUser(HttpUser): wait_time = constant(0.5) tasks = [UserTasks] class StagesShape(LoadTestShape): """ A simply load test shape cla...
49
1,473
locust
examples/custom_shape/step_load.py
.py
from locust import HttpUser, LoadTestShape, TaskSet, constant, task import math class UserTasks(TaskSet): @task def get_root(self): self.client.get("/") class WebsiteUser(HttpUser): wait_time = constant(0.5) tasks = [UserTasks] class StepLoadShape(LoadTestShape): """ A step load s...
44
900
locust
examples/grpc/hello_server.py
.py
import logging import time from concurrent import futures import grpc import hello_pb2 import hello_pb2_grpc logger = logging.getLogger(__name__) class HelloServiceServicer(hello_pb2_grpc.HelloServiceServicer): def SayHello(self, request, context): name = request.name time.sleep(1) retur...
30
751
locust
examples/grpc/locustfile.py
.py
from locust import events, task import gevent import grpc_user import hello_pb2 import hello_pb2_grpc from hello_server import start_server # Start the dummy server. This is not something you would do in a real test. @events.init.add_listener def run_grpc_server(environment, **_kwargs): gevent.spawn(start_server...
23
542
locust
examples/grpc/grpc_user.py
.py
from locust import User from locust.exception import LocustError import time from collections.abc import Callable from typing import Any import grpc import grpc.experimental.gevent as grpc_gevent from grpc_interceptor import ClientInterceptor # patch grpc so that it uses gevent instead of asyncio grpc_gevent.init_ge...
65
1,920
locust
examples/sdk_session_patching/session_patch_locustfile.py
.py
import locust from locust.user import task from archivist.archivist import Archivist # Example library under test class ArchivistUser(locust.HttpUser): def on_start(self): AUTH_TOKEN = None with open("auth.text") as f: AUTH_TOKEN = f.read() # Start an instance of of the lib...
25
761
locust
examples/web_ui_auth/custom_form.py
.py
""" Example of implementing authentication with a custom form for Locust when the --web-login flag is given This is only to serve as a starting point, proper authentication should be implemented according to your projects specifications. For more information, see https://docs.locust.io/en/stable/extending-locust.html...
112
3,762
locust
examples/web_ui_auth/basic.py
.py
""" Example of implementing authentication for Locust when the --web-login flag is given This is only to serve as a starting point, proper authentication should be implemented according to your projects specifications. For more information, see https://docs.locust.io/en/stable/extending-locust.html#authentication """...
81
2,477
locust
examples/postgres/locustfile.py
.py
from locust import constant, task from locust.contrib.postgres import PostgresUser import os from logging import getLogger logger = getLogger("locust") class MyUser(PostgresUser): wait_time = constant(1) @task def run_select_query(self): # example from https://rnacentral.org/help/public-databas...
37
1,110
locust
examples/custom_xmlrpc_client/server.py
.py
import random import time from xmlrpc.server import SimpleXMLRPCServer def get_time(): time.sleep(random.random()) return time.time() def get_random_number(low, high): time.sleep(random.random()) return random.randint(low, high) server = SimpleXMLRPCServer(("localhost", 8877)) print("Listening on ...
21
470
locust
examples/custom_xmlrpc_client/xmlrpc_locustfile.py
.py
from locust import User, task import time from xmlrpc.client import Fault, ServerProxy class XmlRpcClient(ServerProxy): """ XmlRpcClient is a wrapper around the standard library's ServerProxy. It proxies any function calls and fires the *request* event when they finish, so that the calls get recorded...
67
2,242
locust
examples/mqtt/locustfile_custom_mqtt_client.py
.py
from locust import task from locust.contrib.mqtt import MqttClient, MqttUser from locust.user.wait_time import between import time # extend the MqttClient class with your own custom implementation class MyMqttClient(MqttClient): # you can override the event name with your custom implementation def _generate_...
42
1,367
locust
examples/mqtt/locustfile.py
.py
from locust import task from locust.contrib.mqtt import MqttUser from locust.user.wait_time import between import time class MyUser(MqttUser): host = "localhost" port = 1883 # We could uncomment below to use the WebSockets transport # transport = "websockets" # ws_path = "/mqtt/custom/path" ...
35
1,033
locust
pytest_locust/plugin.py
.py
# This is used in pytest style locustfiles, see examples/test_pytest.py from typing import TYPE_CHECKING import pytest if TYPE_CHECKING: from locust.user.users import User class NoOpEvent: # Fake locust.event.EventHook def fire(self, *, reverse=False, **kwargs): pass _config: pytest.Config # ca...
59
1,669
cs249r_book
mlperf-edu/tools/build_wheel.py
.py
#!/usr/bin/env python3 """Build a wheel from clean setuptools state and reject retired modules.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path import shutil import subprocess import zipfile ROOT = Path(__file__).resolve().parents[1] STALE_BUILD_PATHS = (Pat...
209
7,885
cs249r_book
mlperf-edu/tools/run_reference_sweep.py
.py
#!/usr/bin/env python3 """Produce reviewable multi-run reference evidence through the product path. Each repetition runs in a fresh process using the workload's canonical seed. The tool never patches framework RNG functions. A run is invalid when the report or provenance manifest records a different seed, its manifest...
2,833
112,761
cs249r_book
mlperf-edu/tools/reference_source_lock.py
.py
"""Build and verify the source lock for promoted reference evidence. Reference summaries bind the sweep orchestrator, but benchmark meaning also depends on the contracts, harness, runners, reference implementations, and quality assets used by that orchestrator. This module records that focused measurement surface fro...
796
31,107
cs249r_book
mlperf-edu/tools/check_selection_ledger.py
.py
#!/usr/bin/env python3 from __future__ import annotations import sys from pathlib import Path import yaml ROOT = Path(__file__).resolve().parents[1] LEDGER = ROOT / "registry" / "selection-ledger.yaml" STATUSES = {"admitted", "candidate", "deferred", "rejected"} UPSTREAM_FIELDS = { "authority", "task", ...
130
4,091
cs249r_book
mlperf-edu/tools/workload_status.py
.py
#!/usr/bin/env python3 """Report the status of every registered workload. Reads the registry and the retained evidence only. Runs no workload, fetches no asset, produces no timing. Three dimensions are reported separately, because conflating them is how a workload that is doing fine gets read as unfinished: CONFIG...
431
16,869
cs249r_book
mlperf-edu/tools/check_reference_claims.py
.py
#!/usr/bin/env python3 """Fail closed when public review claims drift from indexed case evidence.""" from __future__ import annotations import argparse import json from pathlib import Path import re import sys from typing import Any, Mapping import yaml ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0,...
473
19,085
cs249r_book
mlperf-edu/tools/generate_docs.py
.py
#!/usr/bin/env python3 """Generate the MLPerf EDU documentation site from the workload registry. Single source of truth ---------------------- Generated benchmark and reference facts come from these project contracts: * ``registry/suites/**`` - per-workload / per-variant benchmark metadata * ``registry/suite...
1,539
58,638
cs249r_book
mlperf-edu/tools/measure_course_budgets.py
.py
#!/usr/bin/env python3 """Measure one-run classroom resource budgets for every functional path.""" from __future__ import annotations import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import shutil import subprocess import sys import ...
237
7,299
cs249r_book
mlperf-edu/tools/audit_tflite_adapter_parity.py
.py
#!/usr/bin/env python3 """Audit MLPerf Tiny PyTorch adapters against their pinned TFLite graphs.""" from __future__ import annotations import argparse import hashlib import json import platform import subprocess from datetime import datetime, timezone from importlib.metadata import version from pathlib import Path fr...
368
12,652
cs249r_book
mlperf-edu/tools/import_provisional_reference_results.py
.py
#!/usr/bin/env python3 """Import a mixed verified/provisional MLPerf EDU reference snapshot. The canonical promotion importer remains intentionally strict and accepts only complete repeated-timing evidence. This companion importer supports a v0.1 draft snapshot without weakening that contract. It records promotion-rea...
706
28,199
cs249r_book
mlperf-edu/tools/import_reference_evidence.py
.py
#!/usr/bin/env python3 """Import a complete, verified MLPerf EDU promotion-evidence set. Raw attempts remain outside the repository because they contain checkpoints and dataset-derived artifacts. This importer independently verifies every retained run, then copies only the immutable evidence summaries and a source loc...
1,512
60,327
cs249r_book
mlperf-edu/tools/build_handoff_manifest.py
.py
#!/usr/bin/env python3 """Build a deterministic manifest for an external reference-evidence handoff. The manifest contains only paths relative to the supplied evidence and package roots. It verifies retained evidence against its historical source commit, checks every byte indexed by each portable package, and records ...
947
39,662
cs249r_book
mlperf-edu/tools/export_flat_registry.py
.py
from __future__ import annotations import argparse from pathlib import Path from typing import Any import yaml from mlperf.registry import PRODUCT_SUITES, Workload, load_registry def main() -> int: parser = argparse.ArgumentParser( description="Export the native registry and packaged data catalogs." ...
114
4,043
cs249r_book
mlperf-edu/tools/sync_verified_baselines.py
.py
#!/usr/bin/env python3 """Synchronize verified registry baselines from the case-level reference index.""" from __future__ import annotations import argparse import json import math import sys from pathlib import Path from typing import Any, Mapping import yaml ROOT = Path(__file__).resolve().parents[1] sys.path.ins...
352
13,656
cs249r_book
mlperf-edu/tools/generate_paper_figures.py
.py
#!/usr/bin/env python3 """Generate the paper's figures from committed evidence and run reports. Four figures, each answering a question a reviewer will ask: fig_quality_vs_target Did the inherited contracts reproduce? Shows every workload's observed value normalised against its own ...
317
11,890
cs249r_book
mlperf-edu/tools/check_site_layout.py
.py
#!/usr/bin/env python3 """Verify the rendered MLPerf EDU site at desktop and narrow viewports.""" from __future__ import annotations import argparse import contextlib import json import socket import sys import threading import time from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib im...
263
10,894
cs249r_book
mlperf-edu/tools/generate_review_packets.py
.py
from __future__ import annotations import argparse import re from pathlib import Path from typing import Any from mlperf.assets import asset_dossier, huggingface_model_dossier from mlperf.edu_cli import public_audit_warnings, workload_run_selector from mlperf.registry import ( Workload, baseline_is_current_re...
518
19,192
cs249r_book
mlperf-edu/tools/check_dashboard_layout.py
.py
#!/usr/bin/env python3 """Capture and verify rendered MLPerf EDU result dashboards.""" from __future__ import annotations import argparse import contextlib import json import re import socket import sys import threading import time from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib imp...
304
12,375
cs249r_book
mlperf-edu/tools/check_taxonomy.py
.py
#!/usr/bin/env python3 """ Registry taxonomy and evidence linter for MLPerf EDU. Enforces three invariants on workloads.yaml: (1) Every workload has a complete `regime` block with all three axes: working_set, arithmetic_intensity, dispatch. (2) Categorical `value` on each axis is one of the allowed strings....
2,204
93,917
cs249r_book
mlperf-edu/tutorials/01_first_benchmark.py
.py
"""MLPerf EDU Tutorial 01. Anatomy of a benchmark run. Launch the interactive notebook with: uv run marimo edit tutorials/01_first_benchmark.py Validate its benchmark and provenance path with: python tutorials/smoke_first_benchmark.py """ import marimo __generated_with = "0.23.13" app = marimo.App(width="...
141
4,061
cs249r_book
mlperf-edu/tutorials/smoke_first_benchmark.py
.py
#!/usr/bin/env python3 """Run and verify the noninteractive path used by Tutorial 01.""" from __future__ import annotations import argparse import json import os from pathlib import Path import subprocess import sys from typing import Any PROJECT_ROOT = Path(__file__).resolve().parents[1] def run_tutorial_benchmar...
127
4,144
cs249r_book
mlperf-edu/tests/test_inference_timing_semantics.py
.py
from __future__ import annotations import json import pytest import torch from mlperf.reference.cloud.nanogpt_decode import NanoGPTDecode from mlperf.reference.cloud.nanogpt_prefill import ( FIXED_PROMPT_SEED, NanoGPTPrefill, fixed_token_prompt, ) from mlperf.registry import load_registry from mlperf.run...
186
6,422
cs249r_book
mlperf-edu/tests/test_sync_verified_baselines.py
.py
from __future__ import annotations from dataclasses import replace from pathlib import Path import sys from mlperf.registry import load_registry, public_contract_issues from tools import check_taxonomy from tools import import_reference_evidence as evidence from tools import sync_verified_baselines as sync def test...
190
7,003
cs249r_book
mlperf-edu/tests/test_tflite_adapter_parity.py
.py
import numpy as np from tools.audit_tflite_adapter_parity import AUDIT_SCHEMA, comparison_summary def test_adapter_audit_schema_is_portable_version(): assert AUDIT_SCHEMA == "mlperf-edu-tflite-adapter-audit/0.2" def test_adapter_comparison_requires_exact_predictions_and_quality(): pytorch = np.asarray([[0....
37
1,401
cs249r_book
mlperf-edu/tests/test_functional_setup.py
.py
from __future__ import annotations from pathlib import Path import pytest from mlperf import edu_cli from mlperf.manifest import verify_provd from mlperf.registry import find_project_root, load_registry FUNCTIONAL_WORKLOADS = ( "code-generation", "function-calling", "recommendation", "image-generat...
67
2,435
cs249r_book
mlperf-edu/tests/test_reference_sweep.py
.py
import argparse import ast import hashlib import importlib.util import json import zipfile from pathlib import Path import pytest SCRIPT = Path(__file__).resolve().parents[1] / "tools" / "run_reference_sweep.py" SPEC = importlib.util.spec_from_file_location("run_reference_sweep", SCRIPT) assert SPEC and SPEC.loader ...
836
28,981
cs249r_book
mlperf-edu/tests/test_reinforcement.py
.py
from __future__ import annotations import hashlib import json from pathlib import Path import pytest from mlperf.runners import reinforcement def test_container_command_requires_gpu_and_immutable_image(tmp_path: Path): image = "registry.example/minigo@sha256:" + "a" * 64 command = reinforcement.build_conta...
127
4,371
cs249r_book
mlperf-edu/tests/test_runner_common.py
.py
import torch from mlperf.runners.common import select_torch_device def test_select_torch_device_honors_explicit_request(monkeypatch): monkeypatch.setenv("MLPERF_EDU_DEVICE", "cpu") assert select_torch_device() == torch.device("cpu") def test_select_torch_device_auto_prefers_cuda(monkeypatch): monkeypa...
34
1,218
cs249r_book
mlperf-edu/tests/test_nanogpt_validation.py
.py
import torch from mlperf.runners.nanogpt import _NonOverlappingTextDataset def test_nanogpt_quality_contexts_cover_targets_once_in_order(): tokens = torch.arange(21) dataset = _NonOverlappingTextDataset(tokens, seq_len=4) targets = torch.cat([dataset[index][1] for index in range(len(dataset))]) ass...
26
801
cs249r_book
mlperf-edu/tests/test_registry.py
.py
import hashlib import json from collections import Counter from copy import deepcopy from dataclasses import replace from importlib import resources from pathlib import Path import pytest from mlperf.assets import asset_dossier, has_asset_dossier from mlperf.registry import ( EDU_SCENARIOS, PROFILES, PUBL...
623
23,921
cs249r_book
mlperf-edu/tests/test_power.py
.py
import time from mlperf.power import PowerMeter def test_power_meter_reports_estimated_energy(): meter = PowerMeter(nominal_watts=10.0) meter.start() time.sleep(0.001) report = meter.stop_report() assert report["source"] == "estimated_nominal" assert report["average_watts"] == 10.0 asser...
16
392
cs249r_book
mlperf-edu/tests/test_training_progress.py
.py
"""Progress reporting must be informative, throttled, silenceable, and inert. The reporter exists so a long run is distinguishable from a hung one. It must never become a second measurement channel, so these tests pin the properties that keep it safe: it writes only to the stream it is given, it can be turned off enti...
78
2,627
cs249r_book
mlperf-edu/tests/test_harness.py
.py
import time import pytest from mlperf.harness import HarnessSample, ScenarioConfig, plan_batches, run_harness def test_offline_harness_batches_samples_deterministically(): seen = [] def handler(samples: list[HarnessSample]): seen.append([sample.id for sample in samples]) return [{"batch_siz...
122
4,257
cs249r_book
mlperf-edu/tests/test_ncf_research_overrides.py
.py
"""The NCF `pro`-profile research overrides. These exist so the learning-rate-schedule hypothesis for the recommendation shortfall can be tested without editing the canonical contract. The property that matters most is the first one: an unset environment must reproduce the contract exactly, or every ablation is measur...
84
3,041
cs249r_book
mlperf-edu/tests/test_paper_figures.py
.py
"""The paper's figures must be reproducible by anyone who has the repository. A figure generated from a scratch directory looks identical in the built PDF to one generated from committed evidence, and the LaTeX build cannot tell the difference. That is how a stale figure survives: `make` verifies that the PDF compiles...
160
6,224
cs249r_book
mlperf-edu/tests/test_runner_model_provenance.py
.py
from pathlib import Path import pytest from mlperf.runners import code_generation, retrieval, text @pytest.mark.parametrize( ("builder", "expected_files"), ( (code_generation._model_file_records, set(code_generation.MODEL_FILES)), (retrieval._model_file_records, set(retrieval.MODEL_FILES)), ...
25
828
cs249r_book
mlperf-edu/tests/test_mlperf_tiny_anomaly.py
.py
from __future__ import annotations import torch from mlperf.reference.tiny.mlperf_tiny_anomaly import MLPerfTinyAnomalyAutoencoder def test_mlperf_tiny_anomaly_preserves_official_shape_and_parameter_count(): model = MLPerfTinyAnomalyAutoencoder().eval() inputs = torch.zeros(2, 640) with torch.inference...
29
766
cs249r_book
mlperf-edu/tests/test_function_calling.py
.py
from __future__ import annotations import hashlib import json from pathlib import Path import pytest from mlperf.runners import function_calling def test_qwen_fc_prompt_matches_pinned_bfcl_shape(): messages = [{"role": "user", "content": "What is the weather in Zurich?"}] functions = [ { ...
183
5,862
cs249r_book
mlperf-edu/tests/test_edu_cli.py
.py
import csv import hashlib import json import os import shutil import subprocess import sys import zipfile from argparse import Namespace from pathlib import Path import pytest from mlperf import assets, edu_cli from mlperf.edu_cli import ( default_collection_for, enrich_report_for_display, package_dataset...
2,491
87,498
cs249r_book
mlperf-edu/tests/test_selection_ledger.py
.py
from __future__ import annotations import yaml from tools.check_selection_ledger import LEDGER, UniqueKeySafeLoader, validate def test_selection_ledger_is_complete(): assert validate() == [] def test_selection_ledger_records_every_portfolio_decision(): data = yaml.load(LEDGER.read_text(encoding="utf-8"), ...
36
1,031
cs249r_book
mlperf-edu/tests/test_handoff_manifest.py
.py
import hashlib import json import zipfile from pathlib import Path import pytest from tools import build_handoff_manifest as handoff SOURCE_SHA = "a" * 40 def _json_bytes(payload: object) -> bytes: return (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode() def _included_file(role: str, path: str...
353
11,880
cs249r_book
mlperf-edu/tests/test_contracts.py
.py
from __future__ import annotations import copy import hashlib from pathlib import Path import pytest from mlperf.contracts import evaluate_promotion_contract from mlperf.registry import Workload, load_registry def _artifact_paths(tmp_path: Path, stem: str) -> dict[str, str]: report_path = tmp_path / f"{stem}_r...
221
7,571
cs249r_book
mlperf-edu/tests/test_taxonomy.py
.py
from __future__ import annotations import copy import hashlib import json import subprocess import sys from pathlib import Path from mlperf.registry import load_registry from tools import check_taxonomy AXES = ("working_set", "arithmetic_intensity", "dispatch") def test_committed_causal_lineage_rechecks_every_bou...
461
15,833
cs249r_book
mlperf-edu/tests/test_course_budgets.py
.py
import json from pathlib import Path import sys ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) import measure_course_budgets as budgets # noqa: E402 def test_directory_bytes_and_report_discovery(tmp_path): output = tmp_path / "run" output.mkdir() (output / "data.bin...
39
1,116
cs249r_book
mlperf-edu/tests/test_minigo_adapter.py
.py
"""The MiniGo adapter must replace the network and nothing else. The value of this workload is that the Go rules, feature planes, MCTS, and professional-move evaluation are MLCommons' code executing unmodified. If the adapter ever grows past the network seam, that claim quietly stops being true, so these tests pin the...
76
2,765
cs249r_book
mlperf-edu/tests/test_generate_docs.py
.py
from __future__ import annotations from collections import Counter import re from pathlib import Path import pytest import yaml from mlperf.registry import load_registry from tools import generate_docs ROOT = Path(__file__).resolve().parents[1] @pytest.fixture(scope="module") def generated_outputs() -> dict[Path,...
315
11,990
cs249r_book
mlperf-edu/tests/test_assignment.py
.py
from pathlib import Path import pytest from mlperf.assignment import evaluate_assignment_contract, load_assignment_contract def test_assignment_contract_fixes_cardinality_quality_and_config(tmp_path: Path): path = tmp_path / "assignment.yaml" path.write_text( """\ schema: mlperf-edu-assignment/0.1 i...
143
3,662
cs249r_book
mlperf-edu/tests/test_manifest.py
.py
import hashlib import json import subprocess from mlperf.manifest import ( INTEGRITY_DIGEST_ALGO, LEGACY_PORTABLE_SIGNATURE_ALGO, LEGACY_PORTABLE_SIGNATURE_DOMAIN, _git_leaf, build_provd, rng_leaf, verify_provd, ) def test_rng_leaf_distinguishes_initial_and_manifest_capture_states(): ...
286
10,640
cs249r_book
mlperf-edu/tests/test_image_generation.py
.py
from __future__ import annotations import hashlib import json import pickle from pathlib import Path import numpy as np import pytest import torch from PIL import Image from mlperf.runners import image_generation class _ZeroDenoiser: sigma_min = 0.002 sigma_max = 80.0 def __init__(self) -> None: ...
327
11,948
cs249r_book
mlperf-edu/tests/test_check_reference_claims.py
.py
from __future__ import annotations from tools import check_reference_claims def test_draft_claim_checker_uses_complete_provisional_index(): # Historical draft evidence remains internally verifiable after benchmark # development moves on. It must not be mistaken for current-source evidence. source_sha, re...
25
926
cs249r_book
mlperf-edu/tests/test_import_provisional_reference_results.py
.py
import json import math from pathlib import Path import pytest from tools import import_provisional_reference_results as provisional from tools import import_reference_evidence as promotion ROOT = Path(__file__).resolve().parents[1] def _run(index: int, *, primary: float, quality: float) -> dict: return { ...
170
5,966
cs249r_book
mlperf-edu/tests/test_paper_macros.py
.py
"""Generated macros the paper cites must exist and keep their rendered form. An undefined macro fails the LaTeX build loudly, which is safe. The dangerous case is quieter: a workload's metric key changes, the percent-versus-decimal branch in the generator flips, and a sentence that read "78.52%" silently renders "0.79...
76
3,081
cs249r_book
mlperf-edu/tests/test_fingerprint.py
.py
from __future__ import annotations import copy import sys from types import SimpleNamespace from mlperf import edu_cli, fingerprint def test_execution_device_annotation_distinguishes_request_from_execution(monkeypatch): monkeypatch.setenv("MLPERF_EDU_DEVICE", "MPS") report = {"backend": "pytorch-mps"} ...
488
17,931
cs249r_book
mlperf-edu/tests/test_educational_entrypoints.py
.py
from __future__ import annotations import json import os from pathlib import Path import subprocess import sys import zipfile import pytest from tools.build_wheel import verify_wheel from tools.check_reference_claims import count_claim_pattern PROJECT_ROOT = Path(__file__).resolve().parents[1] def subprocess_envi...
298
11,258
cs249r_book
mlperf-edu/tests/test_experiment.py
.py
import json import os from pathlib import Path import pytest from mlperf import edu_cli from mlperf.experiment import ( EXPERIMENT_PLAN_SCHEMA, bind_instructor_reference, load_experiment_plan, ) def write_plan(tmp_path: Path, body: str) -> Path: path = tmp_path / "plan.yaml" path.write_text(body...
882
27,800
cs249r_book
mlperf-edu/tests/test_environment_reference.py
.py
"""Every environment variable the code reads must be documented. An undocumented knob is worse than a missing one. A researcher cannot find it, and a reader of someone else's result cannot tell whether it was set. Several of these variables change what a workload measures rather than how it runs, so an undocumented on...
91
3,588
cs249r_book
mlperf-edu/tests/test_code_generation.py
.py
from __future__ import annotations import json from pathlib import Path import pytest from mlperf.runners import code_generation def test_official_qwen_prompt_and_stop_rules_match_published_recipe(): prompt = "def add(a, b):\n pass" rendered = code_generation.official_qwen_chatml_prompt(prompt) as...
92
3,300
cs249r_book
mlperf-edu/tests/test_assets.py
.py
import gzip import hashlib import json import shutil import tarfile from pathlib import Path from platformdirs import user_cache_path from mlperf import assets, registry def test_source_checkout_preserves_existing_asset_layout(monkeypatch, tmp_path): source = tmp_path / "mlperf-edu" source.mkdir() (sour...
356
12,911
cs249r_book
mlperf-edu/tests/test_reference_source_lock.py
.py
from __future__ import annotations import copy import json import subprocess from pathlib import Path import pytest from mlperf.registry import load_registry from tools import reference_source_lock ROOT = Path(__file__).resolve().parents[1] def current_commit() -> str: return subprocess.run( ["git", "...
378
12,553
cs249r_book
mlperf-edu/tests/test_mlperf_tiny_vww.py
.py
from __future__ import annotations import torch from mlperf.reference.tiny.mlperf_tiny_vww import MLPerfTinyVWW def test_mlperf_tiny_vww_preserves_official_shape_and_parameter_count(): model = MLPerfTinyVWW().eval() inputs = torch.zeros(2, 3, 96, 96) with torch.inference_mode(): outputs = model...
33
781
cs249r_book
mlperf-edu/tests/test_flat_registry_export.py
.py
"""The packaged flat registry must track the source registry. `workloads.yaml` and its packaged copy are what an installed wheel reads. When they drift from `registry/`, the installed suite runs a different contract than the repository describes, silently. That happened: after recommendation moved from DLRM on Criteo ...
44
1,587
cs249r_book
mlperf-edu/tests/test_import_reference_evidence.py
.py
from __future__ import annotations import copy import json import pytest from tools import import_reference_evidence as importer SOURCE_SHA = "a" * 40 TOOL_SHA = "sha256:" + "b" * 64 FINGERPRINT = "c" * 64 def _host_power() -> dict: snapshot = { "schema": importer.HOST_POWER_STATE_SCHEMA, "pl...
471
16,893
cs249r_book
mlperf-edu/tests/test_ncf_split.py
.py
"""The NCF split must be deterministic under a fixed seed. The evaluation negatives are part of the metric, not an implementation detail: HR@10 is scored against them, so a change in the draw sequence changes the number the 0.635 gate is evaluated against. Memory work on the split has already touched this function onc...
93
3,971
cs249r_book
mlperf-edu/bench/measure_peaks.py
.py
#!/usr/bin/env python3 """ MLPerf EDU: Measure peak FLOPS and peak memory bandwidth for the host. Replaces the hardcoded M1 defaults in src/mlperf/roofline.py. Caches the result keyed by the hardware fingerprint hash so the measurement runs at most once per machine. Per Dean's iter-5 sign-off: needed before iter-6 mea...
146
4,381
cs249r_book
mlperf-edu/examples/lab2_inference_sut.py
.py
#!/usr/bin/env python3 """Lab 2. Compare naïve and KV-cache autoregressive decoding. The lab implements the current :class:`mlperf.sut.SUT_Interface` protocol and drives it locally. The product CLI does not yet accept arbitrary ``--sut`` plugins. Run the canonical built-in inference workload separately with: mlpe...
401
14,909
cs249r_book
mlperf-edu/examples/lab3_arch_comparison.py
.py
#!/usr/bin/env python3 """Lab 3. Compare dense and sparse language-model training systems costs. NanoGPT and Nano-MoE train on the same fixed batches. The lab reports measured loss, throughput, and parameter footprints without claiming that a short run establishes model quality. ``--smoke`` uses deterministic syntheti...
462
16,335
cs249r_book
mlperf-edu/examples/lab1_optimization.py
.py
#!/usr/bin/env python3 """Lab 1. Measure ResNet-18 training-loop optimizations. This lab is an educational experiment, not a score-bearing MLPerf EDU run. Use the product CLI for a canonical image-classification artifact: mlperf run --workload image-classification --profile min The ``--smoke`` path is determinis...
464
15,415
cs249r_book
mlperf-edu/paper/check_paper_pdf.py
.py
#!/usr/bin/env python3 """Fail the paper build on unresolved references, placeholders, or PDF defects.""" from __future__ import annotations import re import sys from pathlib import Path from pypdf import PdfReader def main() -> int: if len(sys.argv) != 3: raise SystemExit("usage: check_paper_pdf.py PD...
92
3,376
cs249r_book
mlperf-edu/paper/generate_registry_snapshot.py
.py
#!/usr/bin/env python3 """Generate paper tables from the registry and draft reference-result index.""" from __future__ import annotations import hashlib import json import math import re import sys from collections import Counter from datetime import datetime from pathlib import Path from typing import Any import ya...
833
33,084
cs249r_book
mlperf-edu/src/mlperf/edu_cli.py
.py
from __future__ import annotations import argparse import copy import csv import hashlib import inspect import json import math import os import platform import posixpath import re import shutil import stat import subprocess import sys import tempfile import time import webbrowser import zipfile from collections.abc i...
9,275
359,138
cs249r_book
mlperf-edu/src/mlperf/contracts.py
.py
from __future__ import annotations import copy import math from dataclasses import replace from pathlib import Path from typing import Any from mlperf.assets import sha256_file from mlperf.registry import QUALITY_BASELINE_ALIASES, Workload PUBLIC_DATA_MODES = { "score-bearing": {"real", "real-preprocessed-mlper...
659
26,853
cs249r_book
mlperf-edu/src/mlperf/assets.py
.py
from __future__ import annotations import csv import gzip import hashlib import io import json import os import shutil import subprocess import sys import tarfile import time import uuid import zipfile import urllib.request from dataclasses import dataclass from pathlib import Path from typing import Any from platfor...
2,561
113,606
cs249r_book
mlperf-edu/src/mlperf/fingerprint.py
.py
""" MLPerf EDU: System Fingerprint Auto-detects hardware and software configuration at runtime. Every benchmark run stamps this into the JSON artifact. No manual hardware claims — all evidence is measured. """ import hashlib import json import os import platform import subprocess from typing import Any FINGERPRINT_...
690
23,984
cs249r_book
mlperf-edu/src/mlperf/manifest.py
.py
""" MLPerf EDU: Provenance manifest with real Merkle-style tamper detection. Replaces the iter-1 era `str(report)` self-hash in loadgen.py with a hash chain that actually binds: source-tree git SHA, weights bytes, dataset bytes, RNG state, hardware fingerprint, and the roofline measurement sidecar. The manifest separ...
1,023
37,873
cs249r_book
mlperf-edu/src/mlperf/__init__.py
.py
"""MLPerf EDU's independent educational benchmark package.""" from .power import PowerMeter __all__ = ["PowerMeter"]
6
119
cs249r_book
mlperf-edu/src/mlperf/assignment.py
.py
from __future__ import annotations import hashlib from pathlib import Path from typing import Any import yaml ASSIGNMENT_SCHEMA = "mlperf-edu-assignment/0.1" SELECTOR_FIELDS = ( "workload", "canonical_workload", "variant", "profile", "mode", "phase", ) def load_assignment_contract(path: Pa...
249
9,461
cs249r_book
mlperf-edu/src/mlperf/registry.py
.py
from __future__ import annotations import math from dataclasses import dataclass from importlib import resources from importlib.metadata import PackageNotFoundError, files from pathlib import Path from typing import Any import yaml from .assets import has_asset_dossier PROFILES = ("min", "max", "pro") PUBLIC_STAT...
1,309
52,755
cs249r_book
mlperf-edu/src/mlperf/loadgen.py
.py
"""Small educational SUT protocol types. MLPerf EDU does not claim to implement the official MLPerf LoadGen API. The types in this module are used by Lab 2 to make query inputs explicit while the lab drives its SUT locally. """ from __future__ import annotations from dataclasses import dataclass from typing import ...
32
684