← Writeups

Code view

ML Orchestration Lab

The lab's scheduling policy and run lifecycle, read in the code: two Kueue ClusterQueues, the one Argo template a GPU job may use, a test that keeps scheduler names out of experiment code, and the SIGTERM path that tells a preemption from a cancel.

The excerpts come from two private repos: homelab-gitops, which holds the cluster's policy, and ml_research, which holds the experiment runtime. They are trimmed to the code; comments and docstrings are left out, and line numbers are the files' own.

01The card is a pool of eight shares

All the GPU quota sits in one ClusterQueue. gpu-tower owns the whole time-sliced pool: eight nvidia.com/gpu shares on the 5060 Ti, plus cpu and memory. Kueue blocks any resource that isn't listed, so cpu and memory have to be covered too.

lendingLimit: "1" is the important line. Of those eight shares, at most one can ever be lent out to the rest of the cohort.

homelab-gitops/scheduling/kueue/clusterqueue.yaml
apiVersion: kueue.x-k8s.io/v1beta2kind: ClusterQueuemetadata:  name: gpu-towerspec:  cohortName: gpu-tower-cohort  namespaceSelector: {}  queueingStrategy: BestEffortFIFO  resourceGroups:    - coveredResources: ["cpu", "memory", "nvidia.com/gpu", "homelab.dev/vram-mib"]      flavors:        - name: nvidia-5060ti          resources:            - name: "cpu"              nominalQuota: "8"            - name: "memory"              nominalQuota: "12Gi"            - name: "nvidia.com/gpu"              nominalQuota: "8"              lendingLimit: "1"

02One language model, enforced by quota

The language models queue through a second ClusterQueue that owns no GPU quota at all. It has nominalQuota: "0" and borrowingLimit: "1", so the most it can ever hold is one share, borrowed from gpu-tower.

A LocalQueue carries no quota of its own, so pointing the LLMs at gpu-tower directly couldn't cap them. That is why "only one model at a time" needs a separate queue. No script enforces it.

homelab-gitops/scheduling/kueue/clusterqueue.yaml
apiVersion: kueue.x-k8s.io/v1beta2kind: ClusterQueuemetadata:  name: gpu-tower-llmspec:  cohortName: gpu-tower-cohort  namespaceSelector: {}  queueingStrategy: BestEffortFIFO  resourceGroups:    - coveredResources: ["cpu", "memory", "nvidia.com/gpu", "homelab.dev/vram-mib"]      flavors:        - name: nvidia-5060ti          resources:            - name: "cpu"              nominalQuota: "4"            - name: "memory"              nominalQuota: "12Gi"            - name: "nvidia.com/gpu"              nominalQuota: "0"              borrowingLimit: "1"            - name: "homelab.dev/vram-mib"              nominalQuota: "0"              borrowingLimit: "12400"

03Memory is counted, not enforced

Shares count pods, but memory is what actually runs out. So the pool also counts a made-up resource, homelab.dev/vram-mib. Its quota is 15,888 MiB: the card's 16 GB minus what the driver reserves. gpu-tower can lend 12,400 MiB of that, which is one LLM's worth, and the LLM queue can borrow exactly that much.

Kueue holds work back when the declared memory isn't free. Nothing stops a process from using more than it declared.

homelab-gitops/scheduling/kueue/clusterqueue.yaml
            - name: "homelab.dev/vram-mib"              nominalQuota: "15888"              lendingLimit: "12400"            - name: "homelab.dev/vram-mib"              nominalQuota: "0"              borrowingLimit: "12400"

04Preemption, and taking the share back

withinClusterQueue: LowerPriority lets a training job evict batch work in the same queue. reclaimWithinCohort on gpu-tower is how training gets the borrowed share back from a running LLM. The LLM is always borrowing, so it can always be reclaimed.

The final block in this file exists because Kueue's webhook refuses borrowWithinCohort unless reclaimWithinCohort is also set. The schema accepts it; only the webhook refuses.

homelab-gitops/scheduling/kueue/clusterqueue.yaml
  preemption:    withinClusterQueue: LowerPriority    reclaimWithinCohort: LowerPriority  preemption:    withinClusterQueue: LowerPriority    reclaimWithinCohort: LowerPriority    borrowWithinCohort:      policy: LowerPriority

05The one door to the card

A workflow step reaches the GPU only through this ClusterWorkflowTemplate. The template sets the Kueue queue label, the priority class and the VRAM declaration from its inputs. An Argo semaphore caps how many GPU steps run at once, before Kueue sees any of them. Infra retries are limited to two, and only on errors.

nvidia.com/gpu: 1 appears here and nowhere in experiment code.

homelab-gitops/workflows/gpu-step.yaml
      metadata:        labels:          kueue.x-k8s.io/queue-name: "{{inputs.parameters.queue-name}}"        annotations:          homelab.dev/gpu-template: gpu-step      priorityClassName: "{{inputs.parameters.priority-class}}"

06Memory and the semaphore

The template patches the pod at submit time with the declared vram-mib, next to the memory limit. The gpu-semaphore ConfigMap key holds the count of GPU steps allowed at once.

homelab-gitops/workflows/gpu-step.yaml
      podSpecPatch: |        runtimeClassName: nvidia        containers:          - name: main            resources:              requests:                memory: "{{inputs.parameters.memory-request}}"              limits:                memory: "{{inputs.parameters.memory-limit}}"                homelab.dev/vram-mib: "{{inputs.parameters.vram-mib}}"            envFrom: {{=toJson(inputs.parameters['secret-name'] == '' ? [] : [{'secretRef': {'name': inputs.parameters['secret-name']} }])}}            volumeMounts: {{=toJson(inputs.parameters['pvc-name'] == '' ? [] : [{'name': 'study-pvc', 'mountPath': inputs.parameters['pvc-mount-path']} ])}}        volumes: {{=toJson(inputs.parameters['pvc-name'] == '' ? [] : [{'name': 'study-pvc', 'persistentVolumeClaim': {'claimName': inputs.parameters['pvc-name']} }])}}      synchronization:        semaphores:          - configMapKeyRef:              name: gpu-semaphore              key: gpu      retryStrategy:        limit: 2        retryPolicy: OnError

07Experiments never name the scheduler

On the other side of the boundary, ml_research has a test that walks the repo. It fails the build if a Kueue, Volcano or Slinky API group, or a raw nvidia.com/gpu request, shows up anywhere outside one exempted adapter package.

The forbidden strings are built from fragments so the test file never trips its own scan.

ml_research/packages/mlr-core/tests/test_portability.py
_EXEMPT_PATH_PREFIXES: tuple[tuple[str, ...], ...] = (("packages", "mlr-homelab", "src"),)def _forbidden_patterns() -> tuple[str, str, str, str]:    kueue = "".join(("kueue", ".", "x-k8s", ".", "io"))    volcano = "".join(("volcano", ".", "sh"))    slinky = "".join(("slinky", ".", "slurm", ".", "net"))    gpu_resource = "".join(("nvidia", ".", "com", "/", "gpu"))    return (kueue, volcano, slinky, gpu_resource)FORBIDDEN_PATTERNS: tuple[str, ...] = _forbidden_patterns()

08The signal handler writes nothing

Preemption, a node drain and a user's cancel all reach the pod as SIGTERM. The handler runs between two bytecodes of whatever the main thread was doing, maybe halfway through a database transaction. So it only records the signal and raises SystemExit(143). The row is closed later, on the way out.

If the signal lands while a run is already writing its close, the handler holds the signal until the commit.

ml_research/packages/mlr-core/src/mlr_core/runtime.py
def _on_sigterm(signum: int, frame: FrameType | None) -> None:    guard = _sigterm    if guard.closing:        guard.pending = (signum, frame)        return    guard.received = signum    previous = guard.previous    if callable(previous):        previous(signum, frame)    raise SystemExit(128 + signum)

09Closing the record on the way out

Run.__exit__ is where the record actually closes. If the exception unwinding through it came from that SIGTERM, the run was stopped from outside. Its status becomes interrupted or cancelled, never failed. That keeps a failure count free of work that was only preempted.

ml_research/packages/mlr-core/src/mlr_core/runtime.py
                if exc_type is not None:                    trace = "".join(traceback.format_exception(exc_type, exc, tb))                    detail = trace[-_FAILURE_DETAIL_MAX:]                if exc_type is not None and guard.received is not None:                    self._close_on_signal(guard.received, trace=detail)                else:

10Cancel or preemption: the mark on the row

The pod can't tell a cancel from a preemption, so mlr runs cancel writes cancel_requested_at on the row before it stops the workflow. The close reads it under a row lock. Mark present: cancelled. Mark absent: interrupted.

It is a compare-and-set on running. If the reaper or a retry has already ended the row, that outcome is kept.

ml_research/packages/mlr-core/src/mlr_core/runtime.py
    def _close_on_signal(self, signum: int, *, trace: str | None) -> None:        try:            with app_session() as s:                row = s.get(models.Run, self.id, with_for_update=True)                if row is None or row.status != "running":                    obs.log.info(                        "run_signal_close_skipped",                        run_id=self.id,                        status=None if row is None else row.status,                    )                    return                outcome = signal_outcome(cancel_requested=row.cancel_requested_at is not None)                row.status = outcome                row.ended_at = datetime.now(UTC)                row.failure_detail = signal_close_detail(                    signum,                    outcome=outcome,                    retry=(row.exec_ref or {}).get("retry"),                    cancel_requested_at=row.cancel_requested_at,                    trace=trace,                )            obs.log.info("run_closed_on_signal", run_id=self.id, status=outcome, signal=signum)        except Exception as exc:            obs.log.warning("run_signal_close_failed", run_id=self.id, error=str(exc))