Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Commits that `git blame` skips. They changed only the format of the code.
# Local git: git config blame.ignoreRevsFile .git-blame-ignore-revs
# GitHub reads this file by its name.

# style: format with ruff 0.17.6 (issue #262)
c7d613ce04a0637ecc71969f6fb840dc9c8e351a
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ trace_collection/post_execution/traces

# uv
.venv/
uv.lock

# act reads these files. They can hold secrets: never commit them.
.secrets
Expand Down
25 changes: 22 additions & 3 deletions doc/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ If you only want to use Chakra, read the [User Guide](../USER_GUIDE.md).
| gate | The full set of local checks. `just gate` runs it. It has the Python checks of CI, and more. |
| recipe | One task in the `justfile`, for example `just lint`. |
| virtual environment | The Python 3.11 install in `.venv/` that `uv` makes. |
| lock file | `uv.lock`. It records the exact version of every package. |
| workflow | One file in `.github/workflows/`. GitHub Actions runs it. |
| act | A tool that runs a workflow in Docker on your computer. |

Expand Down Expand Up @@ -66,17 +67,35 @@ Run `just` to see the list.
| `just test-slow` | Runs the slow tests. They need a network. They build the package as an editable install, and as a wheel that has a file left out. | - |
| `just proto-smoke` | Imports the generated protobuf modules with the newest and the oldest allowed protobuf. | `python_tests.yml` |
| `just wheel-check` | Builds the wheel from a clean copy and installs it (not editable) in a new temporary virtual environment. Checks the wheel files, imports the protobuf modules with two protobuf versions, and starts the commands. The other checks use the editable install. | `python_tests.yml`, `end_to_end_tests.yml` |
| `just lock-check` | Checks that `uv.lock` matches `pyproject.toml`. It fails when they differ. `uv run` and `uv sync` would change an old `uv.lock` without a warning. | - |
| `just gate` | Runs all the checks above. | - |
| `just act` | Runs one workflow in Docker. Add a file name from `.github/workflows/`. The default is `python_lint.yml`. | - |
| `just ci-github-lint` | Lints the workflow files with actionlint in Docker. It fails today, because the workflows use old actions (`checkout@v2`, `setup-python@v2`). It is not part of the gate. | - |

## The lock file

`uv.lock` is in the repository. It records the exact version of every package, for Python 3.11 to 3.14 on all systems. `just setup` and `uv run` use it, so everyone gets the same packages.

When you change `dependencies` or `[dependency-groups]`, run `uv lock` and commit the new `uv.lock`. `just lock-check` shows if you forgot.

## Git blame

A commit that only formats code hides the real author of each line in `git blame`. The file `.git-blame-ignore-revs` lists such commits. GitHub reads it by itself. Tell your local git once:

```bash
git config blame.ignoreRevsFile .git-blame-ignore-revs
```

After a commit that formats many files, add its full hash to the file.

## Common tasks

| Task | How |
|---|---|
| Change a `.proto` file | `just test` rebuilds the generated code. With pip, run `pip install .` again. |
| Add a runtime dependency | Add it to `dependencies` in `pyproject.toml`. |
| Add or change a development tool | Change `[dependency-groups]` in `pyproject.toml` and `requirements-dev.txt`. `just test` fails when they differ. |
| Add a runtime dependency | Add it to `dependencies` in `pyproject.toml`. Run `uv lock`, and commit `uv.lock`. |
| Add or change a development tool | Change `[dependency-groups]` in `pyproject.toml` and `requirements-dev.txt`. Run `uv lock`, and commit `uv.lock`. `just test` fails when the two files differ. |
| Fix a conflict in `uv.lock` | Do not merge it by hand. Take the file from `main`, for example with `git checkout origin/main -- uv.lock`. Then run `uv lock`. |
| Read a host trace in Python | Use `HostTrace.from_file` in `src/host_trace/trace.py`. `chakra_trace_link` and `chakra_converter` both use it. |
| Support a new PyTorch trace format | Add an entry to `FORMAT_CHANGES` in `src/host_trace/versions.py`: the version, the PyTorch release and the keys that each node gains. A new schema number without a format change needs no change. |

Expand Down Expand Up @@ -117,7 +136,7 @@ python -m pytest tests
ruff format --check . && ruff check . && pyright && vulture src/ tests/
```

`pip install .` is not an editable install. Run it again after you change code.
`pip install .` is not an editable install. Run it again after you change code. `pip` does not read `uv.lock`.

## Python version

Expand Down
9 changes: 7 additions & 2 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ lint-scripts:
types:
scripts/run_on_git_files.sh '*.py' -- uv run --isolated --only-group dev pyright

# Unit tests. Use `python -m pytest`, not `pytest`: 3 test files import `src.*`, which needs the repo root on sys.path
# Unit tests, with `python -m pytest` as CI does. Add pytest options after the name, for example `just test -k trace_link`
[positional-arguments]
test *args:
CHAKRA_TOOLING_TESTS=1 uv run python -m pytest -vv tests "$@"
Expand All @@ -50,8 +50,13 @@ proto-smoke:
wheel-check:
scripts/wheel_check.sh

# `uv run` and `uv sync` rewrite a stale uv.lock without a warning. This check fails instead. The gate runs it first.
# Check that uv.lock matches pyproject.toml
lock-check:
uv lock --check

# The full check. Run it before you open a pull request.
gate: lint lint-scripts types test test-slow proto-smoke wheel-check
gate: lock-check lint lint-scripts types test test-slow proto-smoke wheel-check

# It fails now: the workflows use old actions (checkout@v2, setup-python@v2). It is not part of `gate`.
# Lint the GitHub workflow files with actionlint (needs Docker)
Expand Down
11 changes: 8 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,21 @@ exclude = [
]
reportMissingImports = false

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
addopts = "--strict-markers"

[tool.vulture]
ignore_names = ["mock_process_thread"]
min_confidence = 100

# Developer environment for uv (`uv sync`). These pins equal requirements-dev.txt until that file is retired.
[dependency-groups]
dev = [
"pyright==1.1.359",
"pytest==8.1.1",
"ruff==0.3.7",
"pyright==1.1.414",
"pytest==9.2.0",
"ruff==0.17.6",
"vulture==2.11",
"build==1.6.1",
"twine==7.0.0",
Expand Down
6 changes: 3 additions & 3 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pyright==1.1.359
pytest==8.1.1
ruff==0.3.7
pyright==1.1.414
pytest==9.2.0
ruff==0.17.6
vulture==2.11
build==1.6.1
twine==7.0.0
6 changes: 2 additions & 4 deletions src/converter/pytorch_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,8 +414,7 @@ def convert_ctrl_dep_to_data_dep(
if dep_id not in current_node.data_deps:
current_node.data_deps.append(dep_id)
logging.debug(
f"CPU Node ID {current_node.id} now has an inter-thread data dependency on Node ID "
f"{dep_id}"
f"CPU Node ID {current_node.id} now has an inter-thread data dependency on Node ID {dep_id}"
)
if last_visited_non_gpu and last_visited_non_gpu.id not in current_node.data_deps:
current_node.data_deps.append(last_visited_non_gpu.id)
Expand All @@ -435,8 +434,7 @@ def convert_ctrl_dep_to_data_dep(
if prior_node is not None and prior_node.start_time_micros < current_node.start_time_micros:
current_node.data_deps.append(sync_dep)
logging.debug(
f"Node ID {current_node.id} now has an synchonization dependency on Node ID "
f"{sync_dep}"
f"Node ID {current_node.id} now has an synchonization dependency on Node ID {sync_dep}"
)
# Add children to the stack
children_chakra_ids = [child.id for child in json_node.children]
Expand Down
2 changes: 1 addition & 1 deletion src/host_trace/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(self: "HostTrace[HostNode]", raw: Dict[str, Any], source: str = ...
@overload
def __init__(self, raw: Dict[str, Any], source: str = ..., *, node_class: Type[N]) -> None: ...

def __init__(self, raw: Dict[str, Any], source: str = "host trace", node_class: Type[N] = HostNode) -> None:
def __init__(self, raw: Dict[str, Any], source: str = "host trace", node_class: Type[Any] = HostNode) -> None:
self.raw = raw
self.source = source
for key in ("schema", "nodes"):
Expand Down
4 changes: 1 addition & 3 deletions src/trace_link/kineto_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,7 @@ def is_cpu_op(self) -> bool:
"""
simulatable_categories = {"cpu_op", "user_annotation"}
name_exceptions = {"ProfilerStep"}
if self.category in simulatable_categories and all(exc not in self.name for exc in name_exceptions):
return True
return False
return self.category in simulatable_categories and all(exc not in self.name for exc in name_exceptions)

def is_cuda_runtime_op(self) -> bool:
"""
Expand Down
3 changes: 1 addition & 2 deletions src/trace_link/trace_linker.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,8 +599,7 @@ def map_host_to_device_ops(
kineto_op = kineto_rf_id_to_device_op_map[host_op.rf_id]
if kineto_op is None:
logging.warning(
f"No corresponding Kineto op found for Chakra host op ID: {host_op.id}, Name: "
f"'{host_op.name}'."
f"No corresponding Kineto op found for Chakra host op ID: {host_op.id}, Name: '{host_op.name}'."
)
continue
(
Expand Down
73 changes: 68 additions & 5 deletions tests/test_tooling.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,24 @@ def test_uv_installs_the_dev_group_by_default() -> None:
assert "dev" in _pyproject()["tool"]["uv"]["default-groups"]


def test_gitignore_covers_uv_environment_and_lock() -> None:
# Phase 1 does not commit uv.lock (issues #237 and #254 still change the dependencies). Phase 2 removes this line.
def test_pytest_runs_the_tests_folder_and_rejects_unknown_markers() -> None:
# A typo in a marker name must fail at once. Without this option, pytest only warns, and the test runs unmarked.
options = _pyproject()["tool"]["pytest"]["ini_options"]
assert options["testpaths"] == ["tests"]
assert "--strict-markers" in options["addopts"]


def test_pytest_puts_the_repository_folder_on_the_import_path() -> None:
# Some tests import `src.…`. `python -m pytest` finds them, because it adds the current folder to the path.
# Bare `pytest` does not, and then it cannot collect those tests.
assert _pyproject()["tool"]["pytest"]["ini_options"]["pythonpath"] == ["."]


def test_gitignore_covers_the_uv_environment_but_not_the_lock() -> None:
# uv.lock is committed. It records every package of the environment, so that two people get the same one.
lines = {line.strip() for line in (ROOT / ".gitignore").read_text().splitlines()}
assert {".venv/", "uv.lock"} <= lines
assert ".venv/" in lines
assert "uv.lock" not in lines


REQUIRED_RECIPES = {
Expand All @@ -135,6 +149,7 @@ def test_gitignore_covers_uv_environment_and_lock() -> None:
"test",
"gate",
"lint-scripts",
"lock-check",
"wheel-check",
"ci-github-lint",
}
Expand All @@ -145,7 +160,38 @@ def test_justfile_has_the_required_recipes() -> None:


def test_gate_runs_every_check() -> None:
assert {"lint", "lint-scripts", "types", "test"} <= set(_recipes()["gate"])
assert {"lock-check", "lint", "lint-scripts", "types", "test"} <= set(_recipes()["gate"])


def _blame_ignored_commits() -> list[str]:
lines = (ROOT / ".git-blame-ignore-revs").read_text().splitlines()
return [line.strip() for line in lines if line.strip() and not line.startswith("#")]


def test_blame_ignore_file_lists_full_commit_hashes() -> None:
# GitHub reads this file by its name. A short hash does not work in it. Keep one line for each mass-format commit.
commits = _blame_ignored_commits()
assert commits
for commit in commits:
assert re.fullmatch(r"[0-9a-f]{40}", commit), commit


@pytest.mark.skipif(shutil.which("git") is None, reason="needs git")
def test_blame_ignored_commits_are_ancestors_of_head() -> None:
# A rebase or a squash merge changes a hash. The old commit can stay in the local object store, but HEAD no longer
# reaches it, and the line then points at nothing. So check the history of HEAD, not only that the object exists.
shallow = subprocess.run(["git", "rev-parse", "--is-shallow-repository"], cwd=ROOT, capture_output=True, text=True)
if shallow.returncode != 0 or shallow.stdout.strip() != "false":
pytest.skip("needs a git checkout with the full history")
for commit in _blame_ignored_commits():
found = subprocess.run(["git", "merge-base", "--is-ancestor", commit, "HEAD"], cwd=ROOT, capture_output=True)
assert found.returncode == 0, f"{commit} is not in the history of HEAD"


def test_gate_checks_the_lock_before_any_recipe_that_runs_uv() -> None:
# `uv run` and `uv sync` rewrite a stale uv.lock without a warning. So the check must come first.
assert _recipes()["gate"][0] == "lock-check"
assert "uv lock --check" in _recipe_body("lock-check")


def test_every_recipe_has_a_comment() -> None:
Expand All @@ -165,7 +211,7 @@ def test_every_recipe_has_a_comment() -> None:


def test_test_recipe_uses_python_dash_m_pytest() -> None:
# Three test files import `src.*`. Plain pytest cannot find it: it needs the repo root on sys.path.
# CI runs `python -m pytest tests`. The recipe runs the same command.
assert "python -m pytest" in _recipe_body("test")


Expand Down Expand Up @@ -386,6 +432,23 @@ def test_docs_do_not_promise_the_end_of_the_pip_setup() -> None:
assert "retire" not in (ROOT / name).read_text().lower(), f"{name} announces the end of the pip setup"


def test_developer_guide_explains_the_lock_file() -> None:
guide = (ROOT / "doc" / "DEVELOPMENT.md").read_text()
section = _section(guide, "## The lock file")
for text in ("uv.lock", "uv lock", "just lock-check"):
assert text in section
tasks = _section(guide, "## Common tasks")
assert tasks.count("uv lock") >= 3 # new dependency, new tool, and a conflict in uv.lock
assert "by hand" in tasks
assert "uv.lock" in _section(guide, "## The classic setup") # pip does not read it


def test_developer_guide_explains_the_blame_ignore_file() -> None:
section = _section((ROOT / "doc" / "DEVELOPMENT.md").read_text(), "## Git blame")
for text in (".git-blame-ignore-revs", "git config blame.ignoreRevsFile"):
assert text in section


def test_developer_guide_uses_one_word_for_one_meaning() -> None:
# "workflow" is a file in .github/workflows/. The daily steps are not a workflow.
guide = (ROOT / "doc" / "DEVELOPMENT.md").read_text()
Expand Down
7 changes: 7 additions & 0 deletions tests/trace_link/test_kineto_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ def test_is_cpu_op(category, expected):
assert operator.is_cpu_op() == expected


@pytest.mark.parametrize("name, expected", [("ProfilerStep#3", False), ("aten::add", True)])
def test_is_cpu_op_ignores_profiler_steps_by_name(name, expected):
"""A CPU operator whose name holds 'ProfilerStep' is not simulatable."""
operator = KinetoOperator({"cat": "cpu_op", "name": name, "ph": "X", "dur": 1, "ts": 1, "tid": 1, "args": {}})
assert operator.is_cpu_op() is expected


@pytest.mark.parametrize(
"category, expected",
[
Expand Down
Loading
Loading