We are to design an ML experiment tracking CLI with the following features:
- Syncs metadata: meaning it should be able to synchronize metadata (like parameters, metrics, etc.) with a remote server.
- Pushes diff summaries: when an experiment is updated, it should push a summary of the changes (like what changed in the code, data, etc.) to the remote.
- Enforces naming conventions: the CLI should enforce a naming convention for experiments.
Let's break down the design:
We assume a command-line interface (CLI) with the following structure:
ml-track [options] [arguments]
The main commands we might have:
init: Initialize a new experiment (creates a new experiment directory or set of files, and registers the experiment with a unique ID following naming convention).
log: Log metadata (parameters, metrics, etc.) for the current experiment. This command would also be responsible for syncing the metadata to the remote.
push: Push the current state of the experiment (including code, data, and metadata) to the remote. This might include a diff summary.
sync: Sync the local experiment state with the remote (pull changes, resolve conflicts?).
list: List experiments, either locally or on the remote.
status: Show the status of the current experiment (what's changed, what's not synced, etc.)
Naming Conventions:
We can enforce a naming convention for experiment names, for example:
<project_name>--<short_hash>
or
---
But let's make it configurable? Or at least have a default and allow configuration.
However, the requirement says "enforces", so we must have a rule that is not easily bypassed.
Let's assume we have a configuration file (e.g., .mltrackrc) that can set the naming convention pattern, or we have a built-in one.
Example built-in:
experiment_name = -<experiment_type>-
We can break down:
username: from system or config
experiment_type: provided by user at init? or inferred?
timestamp: in a fixed format (e.g., YYYYMMDD-HHMMSS)
But note: we might want to avoid collisions. So we can also include a random string or hash of the code.
However, the requirement is to enforce naming conventions, so we can have:
The experiment name must match a pattern, and the pattern is set in the configuration.
How about:
In the config file, we set:
naming_convention = "{user}-{type}-{date}-{seq}"
And then we have placeholders that are replaced:
{user}: from system or config (could be git user or system user)
{type}: provided by the user (like "image-classification")
{date}: current date in YYYY-MM-DD
{seq}: a sequence number that increments per day per user? or just a random number?
But then we must check that the user-provided name (or the generated one) matches the pattern.
Alternatively, we don't let the user choose the name arbitrarily. We generate it based on the convention and the user only provides the parts that are required.
So at init, we might ask for:
--type <type> (or we can infer from the current directory?)
Then we generate:
<user>-<type>-<date>-<random>
And then we store this as the experiment name.
The experiment name must be stored in a file (like .mltrack/experiment_name) in the project directory.
Then every time we log or push, we use that name.
We also have to check that when we push, the remote doesn't have an experiment with the same name? Or we allow overwriting? Probably not, so we must generate a unique one.
So the sequence or random part is to ensure uniqueness.
Let's do:
naming_convention = "{user}.{type}.{date}.{uuid}"
But we can make it a pattern that the user can set, and we replace the placeholders.
We can have:
{user} -> from config or system
{type} -> provided by user (or from a config in the project?)
{date} -> current date (YYYY-MM-DD)
{time} -> current time (HH-MM-SS)
{uuid} -> a random uuid (or a short hash)
And then we generate the name by:
name = convention.format(user=user, type=type, date=date, time=time, uuid=uuid)
And then we check that the generated name matches the convention? Actually, we generate it so it will.
But what if the user wants to provide a custom name? Then we must validate it against the pattern.
So we can have two modes:
- auto-generated (using the convention and filling the placeholders)
- user-provided, but then we validate against the pattern.
However, the requirement is to enforce naming conventions, so we must not allow a name that doesn't match.
So:
At `init`:
If the user provides `--name <name>`, then we check if it matches the pattern (using the same placeholders?).
But note: the pattern might have placeholders that we expect to be filled. So if the user provides a name, we must check that it matches the pattern without the placeholders?
Actually, the pattern is a string that may contain placeholders. When generating, we replace the placeholders. So the pattern is like a template.
Example pattern: "user.type.date.uuid"
Then the generated name would be: "john.image-classification.2024-01-01.abc123"
If the user provides a name, we must check that it has 4 parts separated by dots? But wait, the pattern might be different.
Alternatively, we can define the pattern as a regex? Then we can check any string against the regex.
So we can have:
In config:
naming_regex = r"^[a-z0-9]+(\.[a-z0-9]+)*$"
But that's too generic.
We want to enforce a specific structure. So let's say:
We have a pattern string that uses {placeholders}. Then we require that the user-provided name must have the same number of parts (separated by the separator, which is also configurable?).
This is getting complicated.
Let's simplify:
We will not allow custom names. The experiment name is always generated automatically by the CLI based on a fixed convention (or a convention set in the config) and the user only provides some parameters (like type) that are used in the generation.
Then the convention is:
[user]-[type]-[date]-[uuid]
And we split by '-'. We require at least 4 parts? But what if the type has a dash? Then we have more parts.
Alternatively, we use a fixed separator (like '.') and require exactly 4 parts? But then the type cannot have a dot.
We can let the user set the separator? And then the pattern is:
{user}{sep}{type}{sep}{date}{sep}{uuid}
Then we generate with a fixed separator (say '.') and the user cannot change the separator? Or we let the user set the separator in the config?
Let's decide:
We have a config that sets:
naming_separator: '.' (default)
naming_parts: ['user', 'type', 'date', 'uuid']
Then we generate by joining the values of these parts with the separator.
And then we validate any provided name (if we allow) by checking that it has exactly 4 parts (if we have 4 parts) and each part matches the expected pattern?
But the user might want to have a different pattern? We are enforcing, so we must be strict.
Given the complexity, I propose:
We do not allow the user to set the experiment name arbitrarily. The experiment name is generated by the CLI at `init` and stored in the experiment's metadata.
The generation rule is:
experiment_name = f"{user}.{type}.{date}.{uuid}"
Where:
user: from config or system (if not set, use current system user)
type: provided by the user (required at init, can be a string without the separator)
date: current date in YYYY-MM-DD
uuid: a random 8-character hex string (or a short uuid)
And we store this in a file: .mltrack/name
Then, when we push, we use that name.
And we enforce that the name must match the pattern: ^[^.]+\\.[^.]+\\.\\d{4}-\\d{2}-\\d{2}\\.[a-f0-9]{8}$
But note: the user might change the system? Or we might want to allow more flexibility?
Alternatively, we can have the pattern as a configurable regex, and then we check the generated name against it. And if the user provides a custom name (via `init --name`), we check against the same regex.
But then we have to store the regex in the config and also in the experiment? Or the experiment must comply with the current config's regex.
This is getting too complex for a simple design.
Let's stick to a fixed convention for now, and then we can make it configurable in the future.
Fixed convention:
experiment_name = <user>.<type>.<date>.<uuid>
where:
user: 1-20 alphanumeric characters (no separator)
type: 1-50 alphanumeric characters and hyphens (but no dot, because dot is separator) -> we replace any dot in type with hyphen?
date: YYYY-MM-DD
uuid: 8 hex characters
We can generate the uuid with:
import uuid
uuid = uuid.uuid4().hex[:8]
Then the regex for validation:
r'^[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9-]{1,50}\.\d{4}-\d{2}-\d{2}\.[a-f0-9]{8}$'
But wait, what if the user's name has a dot? Then we have more parts. So we must sanitize the user and type.
We can:
user = user.replace('.', '-')
type = type.replace('.', '-')
Then we are safe.
So at init:
We ask for a type (or take it from the command line: `ml-track init --type image-classification`)
Then we generate:
user = get_current_user() # from config or system
date = today
uuid = random 8 hex
name = f"{user}.{type}.{date}.{uuid}"
Then we create a directory (or just a metadata file) for the experiment and store the name.
Then, every time we run log or push, we read the name from the local metadata and use it.
Now, for syncing:
We assume there is a remote server (like a REST API) that we can push to and pull from.
We need to have:
- Authentication: maybe via an API token stored in the config.
The `push` command:
- Collects the current experiment's metadata (from the local metadata store, which could be a JSON file or a database? But we are in a CLI, so maybe a JSON file in .mltrack/).
- Also, we want to push a diff summary. What diff?
We are tracking:
- Code: we might have a git repository? Then we can get the diff from the last commit? Or we track the current state of the code?
But the requirement says "pushes diff summaries". So we need to know what changed since the last push.
We can store the last pushed state (like a hash of the code, data, etc.) and then compute the diff.
How to track code:
We can assume the experiment is in a git repository. Then we can get the current commit hash and the last pushed commit hash? But we might not have committed.
Alternatively, we can take a snapshot of the code (like a tarball) and store a hash of it. Then on push, we compute the new hash and if it's different, we note that the code changed.
Similarly for data: we might have a data versioning system (like DVC) or we just track the data files that are in the experiment directory.
But let's not overcomplicate. We'll assume:
The experiment directory has:
.mltrack/
name
last_pushed_commit (if using git)
last_pushed_data_hash (maybe a hash of the data directory)
Then when we push:
We compute the current commit hash (if in git) and compare to last_pushed_commit. If different, we note the code changed and we can get the diff (git diff).
Similarly for data: we compute the hash of the data directory (or of a manifest of data files) and compare.
Then we include in the push:
{
"experiment_name": "user.type.date.uuid",
"metadata": { ... }, # the parameters, metrics, etc.
"code_diff": "...", # if code changed, the diff output
"data_diff": "...", # if data changed, what files changed? or a summary.
}
But note: we might not want to send the entire code diff if it's large. Maybe just a summary (like files changed and number of lines changed).
Alternatively, we can send:
code_changed: true/false
code_diff_summary: "3 files changed, 10 insertions(+), 5 deletions(-)"
And then the remote can store the full diff if needed? Or we don't store the full diff.
Let's decide:
We send a summary of the diff (like the output of `git diff --stat`).
Steps for push:
1. Check that we are in an experiment directory (have .mltrack/name).
2. Read the current state:
- code_hash (current git commit if available, else hash of the code files)
- data_hash (hash of the data directory if tracked)
3. Read the last pushed state from .mltrack/last_pushed_state.json (or separate files)
4. Compute differences.
5. Update the last pushed state to the current state after successful push.
6. Send the metadata and diff summary to the remote.
The remote then stores the experiment with the given name and the metadata and the diff summary.
For log:
We update the local metadata (like parameters and metrics) and then also push? Or just update local and then we have to push separately?
The requirement says "syncs metadata", so maybe `log` should also push? Or we have a separate `sync` that pushes all unsynced logs?
Let's design:
We have a local metadata store (like a JSON file) that we update with `log`.
Then we have a `push` that pushes the current state (including the latest metadata and the diff) to the remote.
Alternatively, we can have `log --sync` to push immediately.
But the requirement says "syncs metadata", so maybe we want to sync the metadata to the remote as part of `log`?
I think we can have:
`log` updates the local metadata and then automatically pushes the metadata (without code and data diff) to the remote?
But then we have two kinds of pushes:
- Metadata push (from `log`)
- Full push (from `push` command that includes code and data diff)
Alternatively, we can have:
`log` only updates local, and then `sync` (or `push`) does both metadata and code/data diff.
Let's read the requirement: "syncs metadata, pushes diff summaries"
It might mean that when we run `push`, we sync the metadata and push the diff summaries.
So:
`push` does:
- Sync the metadata (i.e., send the current parameters and metrics to the remote, updating the remote's copy)
- Push the diff summaries (of code and data)
And `log` only updates the local metadata? Then we might lose metadata if we don't push.
So we can have:
`log` updates local and then also updates the remote? That would be syncing metadata.
But then we are making a network call on every `log`. That might be acceptable.
Alternatively, we can have:
`log` updates local and marks the metadata as unsynced.
Then `push` (or `sync`) will push all unsynced metadata and the diff.
I think the second is better because:
- We might log many times and then push once.
But the requirement says "syncs metadata", which might imply that we want the remote to have the latest metadata promptly.
Let's do:
`log` updates local and then by default does not push. But we can have a `--sync` flag to push immediately.
Then the `push` command will push the metadata (only the unsynced part? or the entire metadata?) and the diff.
How do we track what metadata is unsynced?
We can have a local metadata file that has:
{
"experiment_name": "...",
"parameters": { ... },
"metrics": { ... },
"synced": false # or we can have a separate file that tracks the last synced index?
Alternatively, we can have a log of all the `log` commands (with timestamps) and then when we push, we send all the unsynced logs?
But then the remote must be able to merge? Or we just overwrite the entire metadata?
Let's assume the remote stores the entire metadata for the experiment. Then we can just send the entire current metadata on push.
So:
On `log`:
We update the local metadata (a JSON file) and set a flag that there are unsynced changes.
On `push`:
We read the local metadata, send it to the remote, and then set the flag to false.
And also send the diff summary.
But then if we have multiple `log` without push, we only send the last state? That's acceptable because the remote will have the latest.
However, if we want to track the history of metrics (like each time we log a metric, we want to see the history), then we need to send each log entry.
But that's a different design (like tracking time series). Let's assume we only care about the latest values for parameters and metrics.
So we store:
parameters: { "learning_rate": 0.001, ... }
metrics: { "accuracy": 0.95, ... }
And these are overwritten on each `log`.
Then the remote will have the latest.
If we want history, we might need to store each log as a separate entry? But that's more complex.
Given the scope, let's do:
`log` updates the local metadata (overwriting previous values for the same keys) and marks as unsynced.
`push` sends the entire current metadata and the diff summary, and then marks as synced.
And if we want to keep history, we can have the remote store each push as a version? Then we can have multiple versions per experiment?
But then the experiment name is fixed, so we version by timestamp? Or by a version number?
Alternatively, we can have:
The experiment on the remote has multiple runs? Or we have one experiment per name and we update the metadata and keep a history of the metadata changes?
Let's not overcomplicate. We'll assume one experiment per name and we update the metadata.
But then if we push multiple times, we lose the previous metadata? So we might want to store the history of metadata on the remote.
We can have:
On the remote, for each experiment, we store:
{
"name": "...",
"current_metadata": { ... },
"history": [
{ "timestamp": "...", "metadata": { ... } },
...
]
}
Then when we push, we append the current metadata to the history and update the current_metadata.
But then we are storing a lot of data. Alternatively, we only store the current and the diff of metadata?
Since the requirement says "syncs metadata", we might just sync the current state.
Let's stick to syncing the current state.
Summary of commands:
ml-track init --type <type> [--name <custom_name>]
If --name is provided, validate against the pattern (if we allow custom). But we decided not to allow custom? Let's not allow for now.
Steps:
1. Generate experiment name as per convention.
2. Create .mltrack directory in the current directory (or in a specified directory?).
3. Store the name in .mltrack/name.
4. Create a metadata file: .mltrack/metadata.json with initial empty parameters and metrics? Or we wait for `log` to create?
5. Also create a file for tracking the last pushed state: .mltrack/last_pushed_state.json (initially empty or same as current).
ml-track log --param <key> <value> --metric <key> <value> ...
This updates the local metadata.
We can have:
ml-track log -p learning_rate=0.001 -m accuracy=0.95
Steps:
1. Read .mltrack/name to get experiment name.
2. Read .mltrack/metadata.json (create if not exists).
3. Update the parameters and metrics with the new values.
4. Write back to metadata.json.
5. Set a flag in .mltrack/unsynced = true (or we don't need a flag, we just check on push if the metadata has changed since last push?).
But we also want to track when we logged? Maybe we add a timestamp to each log?
Alternatively, we just overwrite the parameters and metrics.
Let's store:
{
"parameters": { ... },
"metrics": { ... },
"last_logged": "timestamp"
}
And then when we push, we send the entire current state.
ml-track push [--sync-metadata] [--force]
This will:
1. Read the experiment name from .mltrack/name.
2. Read the current state (code and data hashes) and the last pushed state from .mltrack/last_pushed_state.json.
3. Compute the diff summary (if code or data changed).
4. Read the current metadata from .mltrack/metadata.json.
5. Send to the remote:
{
"experiment_name": ...,
"metadata": ...,
"diff_summary": {
"code_changed": true/false,
"code_diff": "...", # summary, like `git diff --stat`
"data_changed": true/false,
"data_diff": "..."
}
}
6. If successful, update .mltrack/last_pushed_state.json with the current state (code_hash, data_hash) and set the metadata as synced (maybe we don't need to track metadata separately because we are sending the entire metadata and the remote will update?).
But note: we are sending the entire metadata every push. So if we have logged multiple times without pushing, we only send the latest.
That's acceptable.
However, if we want to keep the history of metadata on the remote, we might want to send each log entry? But then we need to track what has been sent.
Given the complexity, let's not keep history of metadata. We only keep the latest.
So the remote will have the latest metadata and the latest code and data state.
But then the diff summary is only relative to the last push, so it's a summary of what changed since the last push.
And the metadata is the current state (which might have been logged multiple times).
That's consistent.
ml-track sync
This might be an alias for push? Or it might pull from remote?
The requirement says "syncs", so it might be two-way.
Let's have:
ml-track sync [--pull] [--push]
By default, it does both? Or we can do:
ml-track sync: pull then push?
ml-track sync --push: only push
ml-track sync --pull: only pull
What does pull do?
We might pull the remote's metadata and update our local? But then we might have conflicts.
We can do:
When pulling, we get the remote's current metadata and code/data state? But we don't want to overwrite our local code and data.
So maybe we only pull metadata?
But the remote's metadata might be different from ours (if we logged locally and didn't push, and someone else updated the remote?).
We can do:
On pull: we fetch the remote's metadata and update our local metadata? But then we might overwrite our local logs.
This is tricky.
Given the scope, let's not implement pull for now. We only push.
But the requirement says "syncs", which might imply two-way.
Alternatively, we can have:
The remote is the source of truth. Then we do:
`sync` will:
- Pull the remote's state (metadata, code, data) and overwrite the local? But then we lose local changes.
That doesn't make sense for an experiment tracking.
Another idea:
We track the remote's state (last pushed) and we only push our changes. We don't pull because we assume the experiment is local and we are the only one working on it?
But in a team, multiple people might log to the same experiment? Then we need to pull and merge?
That's too complex.
Let's stick to one-way: local to remote.
So `sync` is an alias for `push`.
Or we can have:
`ml-track sync` does:
- push the current state (metadata and diff) to the remote.
And if we want to get the remote's state, we do `ml-track pull`? But then we overwrite local?
We can have:
`ml-track pull` will:
1. Fetch the remote's current metadata and last pushed state (code and data hashes).
2. Update the local metadata with the remote's? But then we lose local changes.
So we might want to merge? Not trivial.
Given the time, let's not implement pull. We only do push.
Then the requirement "syncs metadata" is satisfied by pushing the metadata to the remote.
And "pushes diff summaries" is also satisfied by push.
So `push` is the command that does both.
Then what about `log`? It only updates local.
So we can have:
ml-track log ... # updates local metadata
ml-track push # pushes the current metadata and diff to remote
And we can combine: `ml-track log ... --push` to do both.
For list:
We can list local experiments (by looking for directories with .mltrack/name) and remote experiments (by querying the remote).
But we might not want to list remote by default because it might be slow.
So:
ml-track list [--local] [--remote]
If neither, then local by default.
For status:
Show the current experiment's status:
- Is there unsynced metadata? (if the local metadata has changed since last push? We don't track that. We only track the last pushed state of code and data, not metadata.)
We can change:
In .mltrack/last_pushed_state.json, we also store the metadata hash? Then we can compare the current metadata hash with the last pushed metadata hash.
Or we can store:
last_pushed_state = {
"code_hash": ...,
"data_hash": ...,
"metadata_hash": ... # hash of the metadata JSON (or a hash of the parameters and metrics dict)
}
Then we can compute the current metadata hash and compare.
Steps for status:
1. Read .mltrack/name.
2. Read current metadata and compute hash.
3. Read last_pushed_state.json and compare the metadata_hash.
4. Also compare code_hash and data_hash (if we are tracking them) to see if code or data changed.
Then we can show:
Experiment: name
Metadata: synced/unsynced
Code: unchanged/changed
Data: unchanged/changed
Now, let's think about the remote server.
We need a server that can:
- Accept a push with experiment name, metadata, and diff summary.
- Store the experiment (if new) or update the existing one.
- Possibly store the history of pushes? We are not storing history of metadata, but we are storing the diff for each push?
We can store:
For each experiment:
{
"name": "user.type.date.uuid",
"current_metadata": { ... },
"pushes": [
{
"timestamp": ...,
"metadata": { ... }, # the metadata at the time of push? But we are sending the current metadata, which might have been updated multiple times.
"diff_summary": { ... }
}
]
}
Then we can see the history of pushes (which includes the diff and the metadata at that time).
But note: the metadata we send in the push is the current metadata, which might have been updated since the last push.
So we are storing the metadata state at each push, and the diff that was pushed at that time.
That's acceptable.
Implementation details:
We'll have:
.mltrack/
name
metadata.json
last_pushed_state.json
The last_pushed_state.json might look like:
{
"code_hash": "abc123",
"data_hash": "def456",
"metadata_hash": "789012",
"pushed_at": "2024-01-01T12:00:00"
}
How to compute code_hash?
If we are in a git repo, we can use `git rev-parse HEAD` to get the current commit.
But what if we are not in a git repo? Then we can compute a hash of all the code files in the current directory? But that might be heavy.
Alternatively, we can only track code if it's in git? And if not, we skip code diff.
Let's do:
If we are in a git repo, then code_hash = current commit hash.
Else, code_hash = null and we don't track code changes.
How to compute data_hash?
We can have a data directory (like 'data/') and we compute a hash of all the files in it? Again, heavy.
Alternatively, we can use a tool like DVC? But that's out of scope.
Let's not track data by default. We can have a config that specifies which directories to track as data? Then we compute a combined hash of all the files in those directories.
But for simplicity, let's skip data tracking for now.
So we only track code (if in git) and metadata.
Then the diff summary:
code_diff: if code_hash changed, then we run `git diff <last_pushed_commit> HEAD` and take the stat? But we don't store the last_pushed_commit, we store the last_pushed_code_hash.
We can do:
if last_pushed_state exists and last_pushed_state.code_hash is not null and current code_hash is not null and they differ:
code_diff = subprocess.run(["git", "diff", "--stat", f"{last_pushed_state.code_hash}..HEAD"], capture_output=True, text=True).stdout
else:
code_diff = ""
Similarly for data? We don't have data_hash yet.
So we start with:
- code tracking (optional, if in git)
- metadata tracking
Let's design the config:
We have a global config (e.g., ~/.mltrackrc) and a project config (in the project root, .mltrack/config?).
The global config might have:
[remote]
url = https://api.mltrack.com
token = <secret>
[naming]
separator = '.'
parts = ['user', 'type', 'date', 'uuid']
But we are not making it configurable for now.
We can have:
In the project, we have .mltrack/name and .mltrack/config (if we want project-specific config).
But for simplicity, we'll have:
Global config for the remote and maybe the user's name.
Project config for the type? But we provide the type at init.
Steps for the user:
1. Install the CLI.
2. Run `ml-track configure` to set the remote URL and token? Or we set it in the config file.
We can have:
ml-track config --remote-url <url> --token <token>
This writes to ~/.mltrackrc.
3. In a project directory, run:
ml-track init --type image-classification
This creates .mltrack/name with the generated name.
4. Then during training, we log:
ml-track log -p lr=0.001 -m acc=0.95
This updates .mltrack/metadata.json.
5. When we want to push:
ml-track push
This will push the current metadata and the code diff (if any) to the remote.
6. We can check status with:
ml-track status
Now, let's write the code structure:
We'll have a package `mltrack` with:
__main__.py: the entry point for the CLI.
We can use argparse or click. Let's use click for simplicity.
commands/
__init__.py
init.py
log.py
push.py
list.py
status.py
config.py
utils/
__init__.py
config.py # for reading/writing config
experiment.py # for experiment operations (generate name, etc.)
remote.py # for pushing to remote
git.py # for git operations
But note: we are designing, not implementing.
Let's write a high-level design of the commands:
init:
def init(type, name=None):
if name is not None:
if not validate_name(name):
raise Error("Invalid experiment name")
exp_name = name
else:
exp_name = generate_name(type)
create .mltrack directory
write .mltrack/name with exp_name
create .mltrack/metadata.json with {}
create .mltrack/last_pushed_state.json with {}
log:
def log(params, metrics):
read .mltrack/name
read .mltrack/metadata.json
update the params and metrics in the metadata
write back
push:
def push():
read .mltrack/name
read .mltrack/metadata.json
read .mltrack/last_pushed_state.json (if exists)
current_code_hash = get_code_hash() # from git or None
current_data_hash = get_data_hash() # to be implemented, for now None
current_metadata_hash = hash(metadata.json) # we can use hashlib.sha256(json.dumps(metadata, sort_keys=True).encode()).hexdigest()
diff_summary = {
"code_changed": (last_pushed_state.code_hash != current_code_hash) if last_pushed_state and current_code_hash else False,
"code_diff": get_code_diff(last_pushed_state.code_hash, current_code_hash) if (last_pushed_state and current_code_hash and last_pushed_state.code_hash != current_code_hash) else "",
"data_changed": (last_pushed_state.data_hash != current_data_hash) if last_pushed_state and current_data_hash else False,
"data_diff": get_data_diff(last_pushed_state.data_hash, current_data_hash) if (last_pushed_state and current_data_hash and last_pushed_state.data_hash != current_data_hash) else ""
}
payload = {
"experiment_name": exp_name,
"metadata": metadata,
"diff_summary": diff_summary
}
send to remote (POST /experiments/push)
if success:
update last_pushed_state.json with:
code_hash: current_code_hash,
data_hash: current_data_hash,
metadata_hash: current_metadata_hash,
pushed_at: now
status:
def status():
read .mltrack/name
read .mltrack/metadata.json
read .mltrack/last_pushed_state.json
current_metadata_hash = hash(metadata)
code_changed = ... (compare with last_pushed_state.code_hash)
data_changed = ...
metadata_synced = (last_pushed_state.metadata_hash == current_metadata_hash) if last_pushed_state else False
print:
Experiment: name
Code: changed/unchanged
Data: changed/unchanged
Metadata: synced/unsynced
This is a basic design.
We haven't considered:
- What if the experiment is not in a git repo? Then code_hash is None and we don't track code.
- What about data? We haven't implemented get_data_hash and get_data_diff. We can leave it for future.
- What about multiple people pushing to the same experiment? We are overwriting the remote's current_metadata and appending to the pushes list.
But note: if two people push at the same time, we might have race conditions.
We can use a version number? Or we can have the remote store the last pushed state and when we push, we send the last known state (the one we pulled) and the remote checks if it's the same?
That's optimistic locking.
We can do:
When we push, we send:
{
"experiment_name": ...,
"metadata": ...,
"diff_summary": ...,
"base_state": { # the state we are basing on (the last_pushed_state we have)
"code_hash": ...,
"data_hash": ...,
"metadata_hash": ...,
"pushed_at": ... # the timestamp of the last push we have
}
}
Then the remote checks if the base_state matches the current state of the experiment. If not, it rejects the push and we have to pull and merge?
But we are not doing pull, so we just fail and ask the user to pull?
Since we don't have pull, we can just overwrite? But then we might lose someone else's changes.
Given the scope, let's not handle concurrency. We assume one person per experiment.
Or we can have the remote always accept the push and append to the history, but update the current_metadata to the new one. Then we lose the previous current_metadata?
But we are storing the history of pushes, so we can recover.
However, the current_metadata is overwritten by the latest push.
So if two people push:
Person A pushes with metadata A1.
Person B pushes with metadata B1.
Then the current_metadata becomes B1, and the history has A1 and B1.
That's acceptable.
But note: the diff_summary for B1 will show the diff from B1's last_pushed_state (which might be the same as A1's push? or not).
Actually, B1's last_pushed_state is the state before B1's push. If A1 pushed in between, then B1's last_pushed_state is not the same as the remote's state before B1's push.
So the diff_summary for B1 might be incorrect?
Because the code and data might have changed by A1.
So we need to update B1's last_pushed_state after A1's push? But B1 doesn't know about A1's push.
Therefore, we should not rely on the last_pushed_state for diff if multiple people are pushing.
Given that, maybe we should not store the last_pushed_state locally and then compute the diff relative to the remote's state?
But then we need to pull first to get the remote's state.
So we change:
On push:
We first get the remote's current state (code_hash, data_hash, metadata_hash) and then compute the diff relative to that.
Then we push our current state and the diff.
Then we update our local last_pushed_state to the remote's state after push? But note: the remote might have changed by someone else in between.
This is getting too complex.
Let's stick to single user per experiment.
We can enforce that by having the experiment name unique and only one person works on it?
Or we can have the remote reject a push if the base_state doesn't match? Then we have to pull first.
Since we don't have pull, we can implement:
push:
get the remote's current state (code_hash, etc.) -> call it remote_state.
compute diff relative to remote_state.
then push, and the remote will update the current_state to our new state.
then update our local last_pushed_state to the new state (the one we just pushed).
But if someone else pushed in between, then our diff will be relative to the state before their push? That might be wrong.
Example:
Remote state: S0
We compute diff from S0 to our local state S1.
Then we push, but in the meantime, someone else pushed and the remote state is now S2.
Then we push, and the remote will set the current state to S1, but the history will have:
S0 -> S2 -> S1
And our diff (from S0 to S1) might not be accurate because S2 happened in between.
So we should do:
We get the remote state (S0) and then we push only if the remote state is still S0? Otherwise, we fail and ask to pull.
That's optimistic locking.
We can change the push to:
payload = {
"experiment_name": ...,
"metadata": ...,
"diff_summary": ...,
"base_state": remote_state # the state we got from the remote
}
The remote checks if its current state matches base_state. If yes, it updates and returns success. If not, it returns an error.
Then we can retry: first pull (get the new remote state) and then compute the diff again? But we don't have pull.
So we can have:
ml-track sync: which does:
while True:
get remote_state
compute diff from remote_state to local_state
try to push with base_state=remote_state
if success, break
else:
# the remote state changed, so we update our local state? But we don't want to overwrite our local code and metadata.
# we only want to update our last_pushed_state? But then we have to recompute the diff?
Actually, if the remote state changed, it means someone else pushed. We want to incorporate their changes?
We can:
1. Get the remote's current state (after their push) and update our last_pushed_state to that? But then our code and data might be different.
This is getting too complex for a simple design.
Given the time, we'll assume single user per experiment and no concurrency.
So we don't check the remote state. We just push and update our local last_pushed_state to our current state.
Then if someone else pushes, the next person to push will have a last_pushed_state that is not the same as the remote's current state, but they will push anyway and overwrite.
We accept that.
So the design is for single user.
Now, let's write the design in a structured way.
We'll have:
Commands:
init:
- Generate experiment name (if not provided) and validate.
- Create .mltrack directory and files.
log:
- Update local metadata.
push:
- Compute code diff (if in git) and data diff (if we implement data tracking).
- Send experiment name, metadata, and diff summary to remote.
- Update last_pushed_state.
status:
- Show the status of the current experiment (unsynced metadata, code changes, data changes).
list:
- List experiments (local or remote).
config:
- Set global configuration (remote URL, token, user name, etc.)
We'll also have:
A function to generate experiment name:
def generate_experiment_name(type):
user = get_user_from_config_or_system()
date = datetime.now().strftime("%Y-%m-%d")
uuid = uuid4().hex[:8]
return f"{user}.{type}.{date}.{uuid}"
A function to validate experiment name:
We have a fixed pattern: r'^[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9-]{1,50}\.\d{4}-\d{2}-\d{2}\.[a-f0-9]{8}$'
But note: the user part is from the config, so it should be safe. The type we provide, and we replace any '.' with '-'. The date is fixed. The uuid is hex.
So the generated name will match.
If the user provides a custom name, we check against the same pattern? But then the user might not know the pattern.
Since we don't allow custom, we don't need to validate user-provided names.
We are done.
However, note: the requirement says "enforces naming conventions". We are enforcing by generating the name and not allowing the user to set it arbitrarily.
But what if the user wants to set the type? The type is part of the name. We must validate the type:
type must be 1-50 alphanumeric and hyphens.
We can sanitize: type = re.sub(r'[^a-zA-Z0-9-]', '-', type)
Then we use that.
So:
type = sanitize_type(type)
Then generate.
This design is for a single user, single machine (though we can have multiple experiments on the same machine) and we push to a remote.
We haven't defined the remote API. We assume there is an endpoint:
POST /api/v1/experiments/push
with JSON body:
{
"experiment_name": "john.image-classification.2024-01-01.abc12345",
"metadata": {
"parameters": { ... },
"metrics": { ... }
},
"diff_summary": {
"code_changed": true,
"code_diff": " file1 | 2 +-\n file2 | 5 ++-",
"data_changed": false,
"data_diff": ""
}
}
And the remote will store the experiment and the push.
We also need an endpoint to list experiments:
GET /api/v1/experiments
returns list of experiment names? or more details?
And maybe an endpoint to get the experiment details:
GET /api/v1/experiments/<name>
But we don't need that for the basic design.
This should cover the requirements.
Let's write the design in a markdown document.
Note: We are not implementing, just designing.
We'll write:
- Overview
- Commands
- Configuration
- Experiment Naming
- Remote API
- Data Structures (local files)
Let's do it.
I'll design a comprehensive ML experiment tracking CLI that addresses your requirements. Here's a structured solution:
ML Experiment Tracker CLI (mlx)
Architecture Overview
┌─────────────────┐ ┌──────────────┐ ┌─────────────┐
│ Local ML │ │ mlx CLI │ │ Remote │
│ Project ├───►│ ├───►│ Storage │
│ │ │ │ │ + API │
└─────────────────┘ └──────────────┘ └─────────────┘
▲ │
│ ▼
┌─────────────────┐ ┌──────────────┐
│ Git/Code │ │ Local │
│ Repository │ │ Metadata │
└─────────────────┘ └──────────────┘
1. Core Commands
mlx init - Initialize Experiment
mlx init --name <experiment_name> --project <project_name> [--config <path>]
mlx log - Log Metadata
mlx log --param key=value --metric key=value [--step <n>] [--file <file>]
- Appends to
metrics.json and params.json
- Automatically timestamps entries
- Supports nested parameters:
--param model.layers=5
mlx diff - Generate & Push Diff Summary
mlx diff [--since <commit>] [--output <file>] [--push]
Options:
--since: Compare against specific git commit (default: last mlx push)
--output: Save diff summary to file
--push: Automatically push after generation
Diff Summary Format:
{
"experiment_id": "proj-20240115-resnet50-abc123",
"timestamp": "2024-01-15T14:30:00Z",
"code_diff": {
"files_changed": 3,
"insertions": 45,
"deletions": 12,
"file_list": ["model.py", "train.py", "utils.py"]
},
"data_diff": {
"dataset_version": "v2.1",
"samples_added": 1500,
"features_changed": ["new_augmentation"]
},
"param_changes": {
"learning_rate": {"old": 0.001, "new": 0.0001},
"batch_size": {"old": 32, "new": 64}
}
}
mlx sync - Bidirectional Sync
mlx sync [--direction <push|pull|both>] [--experiment <id>] [--force]
- Push: Upload local metadata + diff to remote
- Pull: Download remote changes + merge
- Both: Push then Pull (default)
- Conflict resolution: Last-write-wins with conflict warnings
mlx list - List Experiments
mlx list [--local] [--remote] [--project <name>] [--status <active|completed|failed>]
Shows table with:
- Experiment ID, name, status
- Last sync timestamp
- Parameter/metrics summary
- Git commit SHA
mlx status - Current Experiment Status
mlx status
Shows:
- Current experiment details
- Unsynced changes count
- Git branch/commit
- Artifact locations
2. Naming Convention Enforcement
Pattern: <project>-<YYYYMMDD>-<model_type>-<unique_hash>
Examples:
nlp-20240115-bert-base-7f3a2b
cv-20240114-resnet50-c9e8d1
Validation Rules:
- Project: Only lowercase alphanumeric + hyphens (max 20 chars)
- Date: YYYYMMDD format (auto-validated)
- Model Type: Predefined allowlist or regex
[a-z0-9]+(-[a-z0-9]+)*
- Hash: 6-character hex (auto-generated if missing)
Configurable via mlx config naming:
naming:
pattern: "{project}-{date}-{model}-{hash}"
project_allowlist: ["cv", "nlp", "recommendation"]
model_allowlist: ["resnet50", "bert-base", "gpt-small"]
auto_hash_length: 6
validate_on: ["init", "log"] # When to enforce
Enforcement Points:
init: Validate full name or generate valid one
log: Check experiment name still matches convention
sync: Reject upload if name invalid
3. Metadata Sync Strategy
Local Storage Structure
// .mlx/experiments/<id>/metadata.json
{
"experiment_id": "cv-20240115-resnet50-7f3a2b",
"name": "resnet50_baseline",
"project": "cv",
"status": "running",
"created_at": "2024-01-15T10:00:00Z",
"updated_at": "2024-01-15T14:30:00Z",
"git": {
"branch": "main",
"commit": "a1b2c3d",
"remote": "origin"
},
"params": {
"learning_rate": 0.001,
"batch_size": 32,
"model": {"layers": 50, "pretrained": true}
},
"metrics": [
{"step": 100, "accuracy": 0.82, "loss": 0.45, "timestamp": "..."},
{"step": 200, "accuracy": 0.87, "loss": 0.32, "timestamp": "..."}
],
"artifacts": [
{"path": "models/checkpoint.pt", "hash": "sha256:...", "size": 123456}
]
}
Sync Protocol
-
Push:
- Serialize local metadata to protobuf/JSON
- Compute diff since last sync (using stored
last_sync_commit)
- Compress + upload to remote storage (S3/GCS/Azure)
- Update local
last_sync_commit and synced_at
- Register in remote index
-
Pull:
- Fetch remote index for experiment
- Download newer metadata/artifacts
- Merge strategy:
- Metrics: Append-only (no deletion)
- Params: Last-write-wins with timestamp comparison
- Artifacts: Versioned by hash (deduplicated)
- Write conflict report if timestamps overlap
-
Delta Encoding:
- Store only changed fields since last sync
- Use JSON Patch (RFC 6902) for efficient transfers
4. Remote Backend Interface
Supported Backends
- Local Filesystem (default for development)
- S3/GCS/Azure Blob + DynamoDB/CosmosDB index
- MLflow Tracking Server (adapter)
- Custom HTTP API (OpenAPI spec provided)
Required Remote Endpoints
POST /api/v1/experiments # Register new experiment
GET /api/v1/experiments/<id> # Get experiment metadata
PUT /api/v1/experiments/<id> # Update (with If-Match for concurrency)
POST /api/v1/experiments/<id>/diff # Push diff summary
GET /api/v1/experiments?project=<name> # List by project
Authentication
- API Key in header:
Authorization: Bearer <token>
- Or IAM roles for cloud backends
- Token stored encrypted in
~/.mlx/credentials
5. Implementation Highlights
Git Integration
def get_code_diff(base_commit, head_commit):
"""Generate structured diff summary"""
diff = git.diff(base_commit, head_commit, stat=True)
return {
"files_changed": len(diff),
"insertions": sum(change.insertions for change in diff),
"deletions": sum(change.deletions for change in diff),
"file_list": [f.path for f in diff],
"important_files": detect_important_changes(diff) # model.py, config.yaml, etc.
}
Naming Validation
import re
from datetime import datetime
def validate_experiment_name(name, config):
pattern = config.naming.pattern
# Replace placeholders
placeholders = {
'project': r'[a-z0-9-]{1,20}',
'date': r'\d{8}',
'model': r'[a-z0-9-]+',
'hash': r'[a-f0-9]{6}'
}
regex = pattern
for ph, regex_ph in placeholders.items():
regex = regex.replace(f'{{{ph}}}', regex_ph)
if not re.fullmatch(regex, name):
raise ValidationError(f"Name '{name}' doesn't match pattern {pattern}")
# Additional checks
parts = name.split('-')
if len(parts) != 4:
raise ValidationError("Must have exactly 4 parts separated by '-'")
# Validate date
try:
datetime.strptime(parts[1], '%Y%m%d')
except ValueError:
raise ValidationError("Invalid date format, use YYYYMMDD")
Conflict Detection
def detect_conflicts(local_meta, remote_meta):
conflicts = []
# Check metrics with same step
local_steps = {m['step']: m for m in local_meta.get('metrics', [])}
remote_steps = {m['step']: m for m in remote_meta.get('metrics', [])}
for step in set(local_steps) & set(remote_steps):
if local_steps[step]['timestamp'] < remote_steps[step]['timestamp']:
conflicts.append({
'type': 'metric',
'step': step,
'local_time': local_steps[step]['timestamp'],
'remote_time': remote_steps[step]['timestamp']
})
return conflicts
6. Configuration Files
~/.mlx/config.yaml (Global)
default_backend: local
remote:
type: s3
bucket: ml-experiments
region: us-west-2
index_table: experiment_index
naming:
pattern: "{project}-{date}-{model}-{hash}"
auto_hash: true
project_allowlist: ["cv", "nlp", "rl"]
display:
table_columns: ["id", "name", "status", "last_sync", "accuracy"]
default_format: table # or json, yaml
.mlx/config.yaml (Project-specific)
project: "cv-image-classification"
default_experiment_name: "resnet50-baseline"
track_artifacts: ["models/", "data/"]
ignored_paths: [".git", "__pycache__", "*.pyc"]
auto_log:
enabled: true
git_commit: true
system_metrics: ["cpu", "gpu", "memory"]
7. Example Workflow
# 1. Initialize
mlx init --name "resnet50-baseline" --project "cv"
# 2. During training
for epoch in {1..10}; do
mlx log --metric accuracy=$accuracy --metric loss=$loss --step $epoch
done
# 3. Generate and push diff
mlx diff --since HEAD~3 --push
# 4. Check status
mlx status
# Output:
# Experiment: cv-20240115-resnet50-7f3a2b
# Status: Running (3 hours)
# Unsynced: false
# Code changes: 2 files (model.py, train.py)
# Last sync: 2 minutes ago
# 5. List all experiments
mlx list --project cv --status running
8. Error Handling & Validation
Naming Conventions Errors
- Error Code:
MLX_NAME_001 - "Invalid characters in project name"
- Error Code:
MLX_NAME_002 - "Date must be YYYYMMDD format"
- Error Code:
MLX_NAME_003 - "Model type not in allowlist"
Sync Errors
MLX_SYNC_001: "Remote conflict detected. Run mlx sync --pull first"
MLX_SYNC_002: "Authentication failed. Run mlx auth login"
MLX_SYNC_003: "Experiment not found on remote"
Recovery Commands
mlx repair --experiment <id> # Fix corrupted local metadata
mlx reset --experiment <id> # Reset to last known good state
mlx audit --experiment <id> # Show full history/log
9. Extensibility Points
- Plugin System:
mlx plugins install <plugin> for custom backends
- Hooks: Pre/post log/push hooks (
.mlx/hooks/)
- Custom Diff Generators: For data versioning tools (DVC, Pachyderm)
- Webhooks: Notify Slack/Teams on experiment completion
10. Security Considerations
- Secrets Management: Never log API keys/tokens; use
mlx auth with OAuth
- Data Encryption: Encrypt artifacts at rest (AES-256)
- Access Control: RBAC via remote backend (IAM roles)
- Audit Trail: Immutable diff history with SHA-256 hashes
- Compliance: GDPR-ready with
mlx delete --experiment <id> --hard
This design provides:
- ✅ Metadata sync with delta encoding
- ✅ Diff summaries with code/data/parameter changes
- ✅ Naming enforcement with configurable patterns
- ✅ Git integration for code tracking
- ✅ Extensible architecture for different backends
- ✅ Conflict detection and resolution
- ✅ Production-ready with error handling and audit trails
The CLI balances simplicity for quick experiments with robustness for team collaboration, while enforcing consistency through naming conventions and providing clear visibility into changes via diff summaries.