diff --git a/K8S.md b/K8S.md index cbd16960..70b45184 100644 --- a/K8S.md +++ b/K8S.md @@ -12,10 +12,11 @@ How morca will create the pods a run needs, what that takes on AWS, how its cost |---|---| | A Pod and a Service for the dista head | The Service gives the head a DNS name, which becomes `DISTA_HEAD` | | N worker Pods, sized for the pipeline | dista's workers: the pipeline's image with `DISTA_ROLE=worker` | +| The worker Pods of each [worker group](docs/morca-toml.md#groups-off-a-pool) | Its MAX of workers, sized for the group, with `DISTA_GROUP` and the group's GPUs as `nvidia.com/gpu` | | A Job for the driver | The pipeline binary: `taxi run ...`, or `taxi resume ` | | A Secret, for a run with secrets | The values of its `secrets`, which its pods refer to by name | -Every pod also gets the bucket: the scheduler's `AWS_REGION`, `AWS_ENDPOINT_URL_S3` and the like, and `MORCA_WAREHOUSE` and `MORCA_LOGS` when they're in object storage, so steps reach the warehouse and attempts' logs and timelines go to the bucket. The S3 keys come from the stack's Secret `morca-s3` in `morca-runs` (`MORCA_RUN_S3_SECRET`) by `secretKeyRef`, so no Job or Pod object holds them. Before a run's objects go, the scheduler keeps its driver's, head's and workers' logs beside its attempts' (`driver.log`, `head.log`, `worker-.log`). +Every pod also gets the bucket: the scheduler's `AWS_REGION`, `AWS_ENDPOINT_URL_S3` and the like, and `MORCA_WAREHOUSE` and `MORCA_LOGS` when they're in object storage, so steps reach the warehouse and attempts' logs and timelines go to the bucket. The S3 keys come from the stack's Secret `morca-s3` in `morca-runs` (`MORCA_RUN_S3_SECRET`) by `secretKeyRef`, so no Job or Pod object holds them. Before a run's objects go, the scheduler keeps its driver's, head's and workers' logs beside its attempts' (`driver.log`, `head.log`, `worker-.log`, `worker--.log`). The scheduler watches the Job, and deletes everything labelled with the run when it ends. diff --git a/changes/613-groups-providers.minor.md b/changes/613-groups-providers.minor.md new file mode 100644 index 00000000..644b43b4 --- /dev/null +++ b/changes/613-groups-providers.minor.md @@ -0,0 +1 @@ +- **Worker groups off pools**: the local runner, `control` and Kubernetes start each group's MAX of workers (GPUs from the scheduler's host, or `nvidia.com/gpu` on Kubernetes), every provider builds its dista environment through one contract, and `ec2` warns that it ignores groups. (#613) diff --git a/docs/groups.md b/docs/groups.md index 84bbdd19..18a2a7b2 100644 --- a/docs/groups.md +++ b/docs/groups.md @@ -1,18 +1,19 @@ # Worker groups and GPUs on pools: a plan -November 27, 2026 · a plan for step 4 of [layers.md](layers.md); PRs 1 -to 4b are built +November 27, 2026 · a plan for step 4 of [layers.md](layers.md); all its +PRs, 1 to 5, are built (November 28) dista now routes a task or an actor to the workers of a named group, reports -demand per group and runs flows (dista #152 to #167). morca can't use any of -it yet: a run asks for a count of workers, a host reports CPUs and memory -only, and no worker is started with a group. This plan closes that for +demand per group and runs flows (dista #152 to #167). Before this plan morca +used none of it: a run asked for a count of workers, a host reported CPUs +and memory only, and no worker was started with a group. This plan closes that for pools, which [layers.md](layers.md) makes the one model, and then for the -other ways a run gets workers. +other ways a run gets workers. Its PRs are built, so it now describes what +exists. -## What exists, and what is missing +## What existed, and what was missing -| Part | Today | Missing | +| Part | Before | Added | |---|---|---| | Request | `workers`, `cpus`, `memory_gb` per pipeline (`Registered`, `Request`) | Workers per group, each group with its own size and GPUs | | Host facts | CPUs and memory, less a reserve (`host_room`), sent with each claim | GPUs | @@ -139,26 +140,41 @@ memory_gb = 16 ## One contract for every provider "Give run R a worker of group G, of this size, from this image, joined to -this head with this token", and "take it back". After the PRs above the -pool path is that contract, in `MemberSpec` and the stop list. The last PR -names it and moves the other providers behind it: +this head with this token", and "take it back". The pool path was that +contract after the PRs above, in `MemberSpec` and the stop list. PR 5 +named it (`morca._internal.provider`) and moved the other providers behind +it: | Provider | Give | Take back | |---|---|---| | Pool host (`morca worker`) | `join_claim` to `MemberSpec` | Drain, then kill | -| Local and `control` | Fork with `Runtime(groups=...)`, sized from the run's grant | The run's end | -| Kubernetes | A worker Pod per member, sized from the group, with `DISTA_GROUP` and `nvidia.com/gpu` | Delete the Pod after a drain | - -- One function builds a dista worker's environment for all three. -- Kubernetes and local get groups but no scaling in this plan: they start - each group at its MAX and MIN respectively. Scaling there follows if the +| Local and `control` | The run's process forks each group's workers (`Runtime(groups=...)`, from `MORCA_GROUPS`), all sharing the run's grant | The run's end | +| Kubernetes | A worker Pod per worker, sized from the group, with `DISTA_GROUP` and `nvidia.com/gpu` | The run's end | + +- One function builds a dista process's environment for all of them, + selected by the provider's name (`cluster_env`, `driver_env`, + `local_env`, `gpu_env`): the `DISTA_*` names, the slots, and the GPUs. +- Kubernetes, local and `control` get groups but no scaling: each starts + every group at its MAX, for the run's life. (This plan first said local + would start each group's MIN, which with no demand to grow it would + leave a group of `0..N` with no worker.) Scaling there follows if the gate needs it. +- On local and `control` the run is admitted as one: its groups' GPUs, a + group's `gpus` for each of its MAX workers, are part of its request and + come from the scheduler's host, counted as a worker counts its own + (`MORCA_HOST_GPUS`, else `nvidia-smi`). Every forked worker sees all of + the run's GPUs, since dista forks them with one environment; dista's + groups keep the model's tasks on the group's workers. A group's `cpus` + and `memory_gb` aren't used there. - The `ec2` placement gets none of this. It is to be retired - ([layers.md](layers.md)), and `register` warns when a pipeline placed on - it declares groups. -- `register` and `config check` warn about group keys a placement ignores. - The full table of keys per placement is - [#369](https://github.com/morca-dev/morca/issues/369), not this plan. + ([layers.md](layers.md)), and `register` and `config check` warn when a + pipeline placed on it declares groups. +- `register` and `config check` also warn about a group's `cpus` and + `memory_gb` on `control`, which ignores them. A pipeline on the default + placement isn't warned: which runner that is is the scheduler's + `MORCA_RUNNER`, which neither command knows. The full table of keys per + placement is [#369](https://github.com/morca-dev/morca/issues/369), not + this plan. ## Not in this plan @@ -179,7 +195,7 @@ names it and moves the other providers behind it: | 3 | Members by group on pools: `run_members`, `join_claim`, `DISTA_GROUP` (done) | `test-run-cluster` with a GPU group on a mixed pair of hosts: the group's task runs only there | | 4a | Demand per group: the head's status with the claim, `decide` per group, the wanted counts in `join_claim` and the pool's demand; MIN honoured; a host with GPUs leaves a run whose groups ask for GPUs to start on one without (done) | `test-run-cluster` with a group of `0..1` that grows from 0 once the head reports its tasks; unit tests of the decision | | 4b | Draining a member when `decide` says a group has too many, and `gpu_machines` in a growing pool; a bound on a host with GPUs deferring (done) | `test-pool-scale` with a mixed pool whose GPU machine grows for a group from 0, is drained when idle and removed while the run goes on; `test-run-cluster` with a member drained mid-run, and a deferral that ends | -| 5 | The contract by name: one environment builder, groups on local, `control` and Kubernetes, warnings for the `ec2` placement | `test-kube`, and a local run with two groups | +| 5 | The contract by name: one environment builder, groups on local, `control` and Kubernetes, warnings for the `ec2` placement (done) | `test-kube`, and `test-grants` with a local and a control-placed run with two groups | Each PR leaves a pipeline without groups behaving as it does today, except for the MIN fix in PR 4a. diff --git a/docs/layers.md b/docs/layers.md index c0e5a885..b6685e21 100644 --- a/docs/layers.md +++ b/docs/layers.md @@ -189,7 +189,7 @@ than the cluster's memory: | 4 | Worker groups and GPUs in requests, grants and `[pools]`; one provider contract | morca | | 5 | The embedding flow and its Ray Data counterpart; measure the gate | census, dista `bench/` | -1 to 3 are done in dista. The plan for 4 is [groups.md](groups.md). +1 to 3 are done in dista, and 4 in morca ([groups.md](groups.md)). 1 to 3 need nothing from morca and run in dista's local mode, so the flow can be measured against Ray Data on one machine before 4 exists. diff --git a/docs/morca-toml.md b/docs/morca-toml.md index 0c536500..ae43d544 100644 --- a/docs/morca-toml.md +++ b/docs/morca-toml.md @@ -43,7 +43,7 @@ hostname = "orca.mlake.dev" |---|---| | `[defaults]` | Values for every pipeline the file names. It doesn't apply to pipelines the file leaves out. | | `[pipelines.]` | One pipeline's own values, by the name its `describe` gives. An empty table is allowed: the pipeline is then "in the file" and gets `[defaults]`. | -| `[pipelines..groups.]` | One group of the pipeline's workers, with its own size and GPUs, used on pools: [Worker groups](#worker-groups). | +| `[pipelines..groups.]` | One group of the pipeline's workers, with its own size and GPUs, used on pools, the local runner, `control` and Kubernetes: [Worker groups](#worker-groups). | | `[pools.]` | A pool of workers: one morca grows and shrinks itself, or, without a `provider`, machines that join by hand. [Worker pools](#worker-pools). | | `[apps.]` | An app beside the UI and what it gets: [Apps](#apps). | | `[datasets.""]` | A dataset's settings: whether visitors see its data. [Datasets](#datasets). | @@ -97,7 +97,7 @@ Each key can go in `[defaults]` or in `[pipelines.]`. - `fills = "all"` for a keyed pipeline, a sensor, or one with no first partition. `morca register` refuses it with the file and line, because it has to see the pipeline first; see [Fills](#fills). - An `env` name that isn't a valid variable name. - An `env` name that looks like a secret (`*TOKEN*`, `*SECRET*`, `*PASSWORD*`, `*DATABASE_URL*`). Put those in `secrets` instead. -- An `env` variable that morca sets itself: `MORCA_DATABASE_URL`, `MORCA_IMAGE`, `MORCA_SECRETS`, `MORCA_WORKERS`, `DISTA_ROLE`, `DISTA_HEAD`, `DISTA_ADVERTISE`, `DISTA_TOKEN`, `DISTA_PORT`, `DISTA_GROUP`, `MORCA_GRANT_CPUS`, `MORCA_GRANT_MEMORY_MB`, `MORCA_GRANT_GPUS`, `CUDA_VISIBLE_DEVICES`, `MORCA_MEMORY_PRESSURE_FILE`. `DISTA_WORKER_SLOTS` isn't one of them: a pipeline sets it (["auto" from the grant](#auto-from-the-grant)). +- An `env` variable that morca sets itself: `MORCA_DATABASE_URL`, `MORCA_IMAGE`, `MORCA_SECRETS`, `MORCA_WORKERS`, `MORCA_GROUPS`, `DISTA_ROLE`, `DISTA_HEAD`, `DISTA_ADVERTISE`, `DISTA_TOKEN`, `DISTA_PORT`, `DISTA_GROUP`, `MORCA_GRANT_CPUS`, `MORCA_GRANT_MEMORY_MB`, `MORCA_GRANT_GPUS`, `CUDA_VISIBLE_DEVICES`, `MORCA_MEMORY_PRESSURE_FILE`. `DISTA_WORKER_SLOTS` isn't one of them: a pipeline sets it (["auto" from the grant](#auto-from-the-grant)). - A [worker group](#worker-groups) without `workers`, with a key it doesn't have, with a name that isn't lowercase letters, digits, `-` and `_` starting with a letter (at most 32), or in `[defaults]`. Each refusal names the file and line, and nothing is registered: @@ -329,8 +329,12 @@ env = { DISTA_WORKER_SLOTS = "auto", GHARCHIVE_PARALLEL = "auto" } which free devices and passes their indexes in `MORCA_GRANT_GPUS` and `CUDA_VISIBLE_DEVICES` (`0,2`). On a host with GPUs, a start granted none gets both variables empty, so it sees no GPU; on a host without, - neither is set. Only a [group](#worker-groups) asks for GPUs, so only a - member of a group on a pool is granted any. + neither is set. Only a [group](#worker-groups) asks for GPUs: on a pool + a member of the group is granted them, and on the local runner and the + control host the run is granted those of all its groups from the + scheduler's host, counted the same way the first time a run asks for + some (an older scheduler, and a run that asks for none, set neither + variable there, as before). ### Worker groups @@ -338,11 +342,12 @@ A pipeline may split its workers into named groups, each with its own size and GPUs ([groups.md](groups.md)). Groups are recorded, shown and exported, and used on a pool: a run of a pipeline placed `worker:` that declares groups spreads over the pool's workers as a cluster, and gets -members of each group ([workers.md](workers.md#members-by-group)). A dista -task names its group (`Task[..., group="gpu"]`) and runs only on a member -of that group; a task that names none runs on the workers with no group. -Every other placement ignores groups for now (local runs, `control`, -Kubernetes and `ec2`). +members of each group ([workers.md](workers.md#members-by-group)). The +local runner, `control` and Kubernetes start each group's workers too, a +fixed count of them ([Groups off a pool](#groups-off-a-pool)). A dista task +names its group (`Task[..., group="gpu"]`) and runs only on a worker of +that group; a task that names none runs on the workers with no group. The +`ec2` placement ignores groups. ```toml [pipelines.embed] @@ -366,9 +371,11 @@ A group's name is lowercase letters, digits, `-` and `_`, starting with a letter, at most 32 bytes. Groups are a pipeline's own: `[defaults]` can't have them, and no flag sets them. They are stored in `orca.pipelines.groups` (migration 70), and `morca config show` lists each -as `groups.`. The `ec2` placement ignores groups, and `morca -register` and `morca config check` warn when a pipeline placed on it -declares some. +as `groups.`. `morca register` and `morca config check` warn when +a pipeline placed on `ec2` declares groups, which that placement ignores +(its tasks of a group fail there: place it on a pool instead), and when a +pipeline placed on `control` gives a group `cpus` or `memory_gb`, which +the control host ignores. On a pool, each group's members are its own: @@ -399,6 +406,34 @@ On a pool, each group's members are its own: such a worker starts a run as a cluster; one without stays queued, held saying so. +#### Groups off a pool + +The local runner, the control host and Kubernetes start each group's +workers beside the workers with no group, from the run's start to its end. +None of them scales: each group gets its MAX (a count is its own), the +MIN of a range is used only where demand is reported, on a pool. + +- **Local runner and `control`.** The run's process forks its dista + workers itself: as before, `MORCA_WORKERS` with no group (control's + `MORCA_CONTROL_WORKERS`), and now also each group's MAX, which it reads + from `MORCA_GROUPS` (`gpu=2,io=1`). The run is admitted and granted as + one: its groups' `gpus` for each of their MAX workers are part of its + request, held from the scheduler's host's GPUs (`MORCA_HOST_GPUS`, else + `nvidia-smi -L`) and given to the run's process in `MORCA_GRANT_GPUS` + and `CUDA_VISIBLE_DEVICES`, which all its workers see. A run that asks + for more GPUs than the host has waits, saying so ("waiting: needs 2 + GPUs, more than the 1 this host grants at most"). A group's `cpus` and + `memory_gb` aren't used: the workers share the run's grant. +- **Kubernetes.** Each worker of a group is a pod of its own, + `morca---worker--` (an `_` in the name becomes + `-`), labelled `orca.group`, with `DISTA_GROUP=`. It is sized as + the pipeline's workers are ([On Kubernetes](#on-kubernetes)) from the + group's `cpus` and `memory_gb`, the pipeline's where it sets none, and a + group's `gpus` are in its limits as `nvidia.com/gpu`, which a cluster + with NVIDIA's device plugin schedules; inside the pod they are numbered + from 0 in `MORCA_GRANT_GPUS` and `CUDA_VISIBLE_DEVICES`. The groups' + pods count towards the run's `cpu_millis` and the vCPU budget. + ### On Kubernetes A run's driver, and each of its dista workers, asks for the pipeline's diff --git a/docs/workers.md b/docs/workers.md index 5ea661e4..b12f63c0 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -362,8 +362,10 @@ reports demand, it starts with MIN and grows by demand. With reporting turned off, or a head on a worker from before this, a range still asks for MAX at once. -Only pools use groups for now: a local run, `control`, Kubernetes and the -`ec2` placement start their workers as before, with no group. +Off a pool, the local runner, `control` and Kubernetes start each group's +MAX of workers for the run's life, without demand +([morca-toml.md](morca-toml.md#groups-off-a-pool)); the `ec2` placement +ignores groups. **On a pool morca grows** (`[pools.]`), this is set up for you: - every Hetzner machine joins a private network of the stack's, and its diff --git a/src/morca/_internal/config.mojo b/src/morca/_internal/config.mojo index 57ec9173..49e39735 100644 --- a/src/morca/_internal/config.mojo +++ b/src/morca/_internal/config.mojo @@ -88,7 +88,7 @@ from morca._internal.fill import ( ) from morca._internal.groups import ( Group, - ec2_ignores_groups, + placement_warnings, groups_json, groups_problem, read_groups, @@ -684,12 +684,12 @@ struct ProjectConfig(Movable): return read_groups(self.doc, pipeline) def group_warnings(self) raises -> List[String]: - """`file:line: [pipelines.] ...` for each pipeline placed on - `ec2` that declares groups, which that placement ignores.""" + """`file:line: [pipelines.] ...` for what each pipeline's + groups are ignored for where it's placed + (`morca._internal.groups.placement_warnings`).""" var out = List[String]() for p in self.pipelines(): - var why = ec2_ignores_groups(p, self.placement(p), self.groups(p)) - if why: + for why in placement_warnings(p, self.placement(p), self.groups(p)): out.append( String( self._loc(["pipelines", p, "groups"]), diff --git a/src/morca/_internal/control.mojo b/src/morca/_internal/control.mojo index 1e8db5f4..31dd017f 100644 --- a/src/morca/_internal/control.mojo +++ b/src/morca/_internal/control.mojo @@ -27,7 +27,8 @@ image's). Small runs then start in a second, without an instance to boot. A run held by either of the last two stays queued with the reason in `runs.held`, which its page and JSON show. dista inside such a run is in -local mode, `MORCA_CONTROL_WORKERS` (1) forked workers. +local mode, `MORCA_CONTROL_WORKERS` (1) forked workers with no group, and +each worker group's MAX (docs/groups.md, `morca._internal.provider`). **Secrets** (`--secret NAME=ID`) are read by the scheduler when it starts the run, with `MORCA_SECRET_FETCH` as the instances read them, else from @@ -45,6 +46,7 @@ from json import loads from morca._internal.awsjson import aws_json from morca._internal.json import quote from morca._internal.proc import binary_seconds, capture +from morca._internal.provider import local_env from morca._internal.system import Now comptime CONTROL = "control" @@ -212,12 +214,15 @@ def run_env( limits: ControlLimits, image: String, secrets: List[Tuple[String, String]], + groups: String = "", ) -> List[String]: """What a control-placed run's process gets beside the scheduler's - environment: its local workers, its image (which its version records) - and its secrets' values, `secrets` being (NAME, value) pairs, named in - `MORCA_SECRETS`.""" - var out: List[String] = [String("MORCA_WORKERS=", limits.workers)] + environment: its local workers and those of its `groups` + (`name=count,...`), as the control provider gives them + (`morca._internal.provider.local_env`), its image (which its version + records) and its secrets' values, `secrets` being (NAME, value) pairs, + named in `MORCA_SECRETS`.""" + var out = local_env(CONTROL, limits.workers, groups) if image: out.append(String("MORCA_IMAGE=", image)) out.extend(secrets_env(secrets)) diff --git a/src/morca/_internal/db/registered.mojo b/src/morca/_internal/db/registered.mojo index 4de5ad73..69723e38 100644 --- a/src/morca/_internal/db/registered.mojo +++ b/src/morca/_internal/db/registered.mojo @@ -70,6 +70,8 @@ struct Registration(Copyable, Movable): var probe_every: Int var groups: String """`orca.pipelines.groups` (`morca._internal.groups`): JSON, or empty.""" + var has_tasks: Bool + """Whether its binary's `describe` lists dista tasks.""" def registrations( @@ -136,7 +138,9 @@ def registrations( " concurrency_key, coalesce(concurrency_limit, 0)::bigint AS" " concurrency_limit, learn_from IS NOT DISTINCT FROM" " 'working_set' AS working_set, coalesce(probe_every, 1)::bigint" - " AS probe_every, coalesce(groups::text, '') AS groups FROM" + " AS probe_every, coalesce(groups::text, '') AS groups," + " jsonb_array_length(coalesce(describe->'tasks', '[]')) > 0 AS" + " has_tasks FROM" " orca.pipelines WHERE binary_path IS" " NOT NULL AND retired IS NULL AND ($1 = '' OR name = $1) ORDER BY" " priority DESC, name" @@ -199,6 +203,7 @@ def registrations( r.bool("working_set"), Int(r.int64("probe_every")), r.text("groups"), + r.bool("has_tasks"), ) ) return out^ diff --git a/src/morca/_internal/db/starting.mojo b/src/morca/_internal/db/starting.mojo index 15b80a91..fc1393c2 100644 --- a/src/morca/_internal/db/starting.mojo +++ b/src/morca/_internal/db/starting.mojo @@ -287,6 +287,7 @@ def mark_started( instance: Int, request_source: String, request_runs: Int, + grant_gpus: Int = 0, ) raises -> Int: """Starts `run` as the scheduler's, with what it was given (empty texts and zeros recorded as none), and returns its new start. Its @@ -303,7 +304,8 @@ def mark_started( " = NULL, request_cpus = nullif($4, '')," " request_memory_gb = nullif($5, '')," " grant_cpus = nullif($6, 0), grant_memory_mb =" - " nullif($7, 0), grant_gpus = NULL, memory_limit_mb = NULL," + " nullif($7, 0), grant_gpus = nullif($11, 0), memory_limit_mb =" + " NULL," " memory_max_mb = NULL, memory_bytes = NULL," " instance = nullif($8, 0), request_source =" " nullif($9, ''), request_runs = nullif($10," @@ -319,7 +321,8 @@ def mark_started( .int64(Int64(grant_memory_mb)) .int64(Int64(instance)) .text(request_source) - .int64(Int64(request_runs)), + .int64(Int64(request_runs)) + .int64(Int64(grant_gpus)), ) .row(0) .int64("starts") diff --git a/src/morca/_internal/groups.mojo b/src/morca/_internal/groups.mojo index 6039777f..5e4b6548 100644 --- a/src/morca/_internal/groups.mojo +++ b/src/morca/_internal/groups.mojo @@ -10,11 +10,23 @@ each with its own size and GPUs, from morca.toml. A group's name is lowercase letters, digits, `-` and `_`, starting with a letter, at most 32 bytes. `register` keeps the groups in `orca.pipelines.groups` (`groups_json`, by name, so the file's order -doesn't matter), and `morca config show` and `export` show them. On a -pool, a run's members are started by group (`morca._internal.member_wants`, -`morca._internal.run_cluster`); the other placements ignore groups for -now, and `register` warns of the `ec2` placement's -(`ec2_ignores_groups`). +doesn't matter), and `morca config show` and `export` show them. Each +provider (`morca._internal.provider`) starts a run's workers by group: + +- On a pool, a run's members (`morca._internal.member_wants`, + `morca._internal.run_cluster`), each group's MIN growing to its MAX with + its head's demand. +- On the local runner and the control host, the run's process forks each + group's MAX (`local_groups`), beside its workers with no group. The run + is admitted and granted as one, with the GPUs of all its groups + (`local_gpus`); a group's `cpus` and `memory_gb` aren't used there. +- On Kubernetes, a worker Pod per worker of each group's MAX, sized from + the group, with `nvidia.com/gpu` for its GPUs + (`morca._internal.kube_size.GroupPods`). + +None of the last two scale. The `ec2` placement ignores groups, and +`register` and `config check` warn of it, and of a group's sizes on the +control host (`placement_warnings`). """ from json import loads @@ -341,6 +353,52 @@ def parse_groups(text: String) raises -> List[Group]: return out^ +def local_groups(groups: List[Group]) -> String: + """`MORCA_GROUPS` for a run that forks its workers (morca.tasks): each + group and its MAX, `gpu=2,io=1`; empty for none.""" + var text = String() + for g in by_name(groups.copy()): + text.write("," if text else "", g.name, "=", g.max_workers) + return text^ + + +def local_gpus(groups: List[Group]) -> Int: + """The GPUs a run that forks its workers asks for: each group's GPUs + for each of its MAX workers.""" + var n = 0 + for g in groups: + n += g.gpus * g.max_workers + return n + + +def placement_warnings( + pipeline: String, placement: String, groups: List[Group] +) -> List[String]: + """What a pipeline's groups are ignored for where it's placed: all of + them on `ec2`, a group's `cpus` and `memory_gb` on the control host, + which grants the run as one.""" + var out = List[String]() + var ec2 = ec2_ignores_groups(pipeline, placement, groups) + if ec2: + out.append(ec2) + if placement == "control": + var sized = String() + for g in groups: + if g.cpus or g.memory_gb: + sized.write(", " if sized else "", g.name) + if sized: + out.append( + String( + pipeline, + " is placed on control, which ignores the cpus and", + " memory_gb of its groups (", + sized, + "): its workers share the run's grant", + ) + ) + return out^ + + def ec2_ignores_groups( pipeline: String, placement: String, groups: List[Group] ) -> String: @@ -355,5 +413,7 @@ def ec2_ignores_groups( pipeline, " declares groups (", names, - ") but is placed on ec2: the ec2 placement ignores groups", + ") but is placed on ec2: the ec2 placement ignores groups, so", + " its tasks of those groups fail; place it on a pool", + " (worker:) instead", ) diff --git a/src/morca/_internal/kube.mojo b/src/morca/_internal/kube.mojo index 4c7a4044..60d48c9d 100644 --- a/src/morca/_internal/kube.mojo +++ b/src/morca/_internal/kube.mojo @@ -9,7 +9,8 @@ was registered with (`morca register --image`): |---|---| | A Job, `morca--` | the driver: ` resume ` | | A Pod and a Service, `morca---head` | the dista head, for a pipeline with tasks | -| `workers` Pods, `morca---worker-` | dista's workers, for a pipeline with tasks | +| `workers` Pods, `morca---worker-` | dista's workers with no group, for a pipeline with tasks | +| Pods `morca---worker--` | each worker group's MAX of workers (docs/groups.md), labelled `orca.group` | All are labelled `orca.run`, `orca.start` (the run's start count), `orca.pipeline` and `orca.role`, and the head, its Service and the workers @@ -19,7 +20,10 @@ are owned by the Job, so deleting the Job deletes them. The Job has retries runs itself. The driver reaches Postgres through the Secret `MORCA_RUN_SECRET` (default `morca-db`, key `url`) in that namespace, and the head through `DISTA_HEAD`; the scheduler's variables named in -`MORCA_RUN_ENV` are copied to every pod. +`MORCA_RUN_ENV` are copied to every pod. The head's and workers' own +variables are the `kubernetes` provider's (`morca._internal.provider`): a +group's workers get `DISTA_GROUP`, and its GPUs as `nvidia.com/gpu` in +their limits. **Object storage.** Every pod gets the scheduler's bucket settings as it has them (`AWS_REGION`, `AWS_DEFAULT_REGION`, `AWS_ENDPOINT_URL`, @@ -108,6 +112,7 @@ from morca._internal.db.live import stale_limit, start_grace from morca._internal.json import quote from morca._internal.kube_size import ( OOM_KILLED, + GroupPods, KubeDefaults, Killed, KubeSizes, @@ -117,8 +122,17 @@ from morca._internal.kube_size import ( pod_killed, pod_memory, pod_stuck, + pod_slugs, stuck_text, ) +from morca._internal.provider import ( + KUBERNETES, + ClusterProcess, + cluster_env, + driver_env, + json_entries, + pod_devices, +) from morca._internal.kube_place import KubePlacement from morca._internal.logs import ( is_remote, @@ -222,6 +236,17 @@ struct RunSpec(Copyable, Movable): pod's NAME refers to, over the variables above of that name.""" var sizes: KubeSizes """Its pods' requests and limits (`morca._internal.kube_size`).""" + var groups: List[GroupPods] + """Its worker groups' pods (docs/groups.md); none without groups.""" + + def has_cluster(self) -> Bool: + """Whether it has a head: workers with no group or in a group.""" + if self.workers > 0: + return True + for g in self.groups: + if g.count > 0: + return True + return False def secret_name(run: Int, start: Int) -> String: @@ -455,12 +480,23 @@ struct KubeRunner(Movable): command: String, env: String, size: PodSize, + gpus: Int = 0, + group: String = "", ) -> String: + var labels = self._labels(r, role) + if group: + var base = labels^ + labels = String( + base[byte = : base.byte_length() - 1], + ', "orca.group": ', + quote(group), + "}", + ) return String( '{"apiVersion": "v1", "kind": "Pod", "metadata": {"name": ', quote(name), ', "labels": ', - self._labels(r, role), + labels, ', "ownerReferences": [', owner, ']}, "spec": {"restartPolicy": "Never"', @@ -472,7 +508,7 @@ struct KubeRunner(Movable): ', "env": ', self._env(r, env), ', "resources": ', - size.resources(), + size.resources(gpus), "}]}}", ) @@ -509,7 +545,7 @@ struct KubeRunner(Movable): if r.allow_new_code: args.append("--allow-new-code") var argv = _command(args^, masked) - var driver_env = String( + var own = String( '{"name": "MORCA_DATABASE_URL", "valueFrom": {"secretKeyRef":', ' {"name": ', quote(self.secret), @@ -519,14 +555,10 @@ struct KubeRunner(Movable): quote(r.image), "}", ) - if r.workers > 0: - driver_env.write( - ', {"name": "DISTA_HEAD", "value": "', - head, - ":", - DISTA_PORT, - '"}', - ) + var head_at = String(head, ":", DISTA_PORT) + var joins = driver_env(KUBERNETES, head_at if r.has_cluster() else "") + if len(joins) > 0: + own.write(", ", json_entries(joins)) var job = String( '{"apiVersion": "batch/v1", "kind": "Job", "metadata": {"name": ', quote(name), @@ -544,7 +576,7 @@ struct KubeRunner(Movable): ', "imagePullPolicy": "IfNotPresent", "command": ', argv, ', "env": ', - self._env(r, driver_env), + self._env(r, own), ', "resources": ', r.sizes.driver.resources(), "}]}}}}", @@ -559,7 +591,7 @@ struct KubeRunner(Movable): except: pass # sweep's, then raise e^ - if r.workers == 0: + if not r.has_cluster(): return var owner = String( '{"apiVersion": "batch/v1", "kind": "Job", "name": ', @@ -577,11 +609,8 @@ struct KubeRunner(Movable): "head", owner, bin, - String( - '{"name": "DISTA_ROLE", "value": "head"}, {"name":', - ' "DISTA_PORT", "value": "', - DISTA_PORT, - '"}', + json_entries( + cluster_env(KUBERNETES, ClusterProcess.head_at(DISTA_PORT)) ), r.sizes.head, ), @@ -602,6 +631,9 @@ struct KubeRunner(Movable): "}]}}", ), ) + var worker = json_entries( + cluster_env(KUBERNETES, ClusterProcess.worker_of(head_at)) + ) for i in range(r.workers): _ = self.k.create( PODS, @@ -611,18 +643,34 @@ struct KubeRunner(Movable): "worker", owner, bin, - String( - '{"name": "DISTA_ROLE", "value": "worker"}, {"name":', - ' "DISTA_HEAD", "value": "', - head, - ":", - DISTA_PORT, - '"}, {"name": "DISTA_ADVERTISE", "valueFrom":', - ' {"fieldRef": {"fieldPath": "status.podIP"}}}', - ), + worker, r.sizes.worker, ), ) + # Each group's workers (docs/groups.md): its own size, DISTA_GROUP + # and its GPUs, which the pod sees numbered from 0. + var slugs = pod_slugs(r.groups) + for k in range(len(r.groups)): + ref g = r.groups[k] + var p = ClusterProcess.worker_of(head_at, group=g.group) + p.gpus = True + p.devices = pod_devices(g.gpus) + var env = json_entries(cluster_env(KUBERNETES, p)) + for i in range(g.count): + _ = self.k.create( + PODS, + self._pod( + r, + String(name, "-worker-", slugs[k], "-", i), + "worker", + owner, + bin, + env, + g.size, + g.gpus, + g.group, + ), + ) def _keep_logs(self, mut db: State, job: Value): """Appends the log of the Job's driver pod to the run's `driver.log` diff --git a/src/morca/_internal/kube_size.mojo b/src/morca/_internal/kube_size.mojo index fb46ba38..9d613c89 100644 --- a/src/morca/_internal/kube_size.mojo +++ b/src/morca/_internal/kube_size.mojo @@ -29,6 +29,12 @@ the limit it was killed at (an eviction: the request it had), at most ask for at least that, requests and limits, until 20 of its runs have succeeded since. One killed at that maximum already fails, unretried. +**Groups.** A worker group's pods (`GroupPods`) are sized the same way +from the group's own `cpus` and `memory_gb`, each the pipeline's where +the group sets none, and a group that asks for GPUs has them in its pods' +limits as `nvidia.com/gpu`. Their requests are part of the run's +`cpu_millis` (`with_groups`). + **Stuck.** A `Pending` pod that no node will take (`Unschedulable`), or whose image can't be pulled or container made (`ImagePullBackOff`, `ErrImagePull`, `CreateContainerConfigError`, ...), is `pod_stuck`: its run @@ -42,6 +48,9 @@ from json import Value from morca._internal.cgroup import raised_mb from morca._internal.resources import Request, gb_text +comptime GPU_RESOURCE = "nvidia.com/gpu" +"""The extended resource a group's GPUs are asked for by (NVIDIA's device +plugin).""" comptime OOM_KILLED = "OOMKilled" comptime EVICTED = "Evicted" @@ -89,8 +98,10 @@ struct PodSize(ImplicitlyCopyable, Movable): var memory_request_mb: Int var memory_limit_mb: Int - def resources(self) -> String: - """The container's `resources`, as JSON.""" + def resources(self, gpus: Int = 0) -> String: + """The container's `resources`, as JSON; with `gpus`, that many + `nvidia.com/gpu` in its limits (Kubernetes takes them as the + request too).""" var out = String( '{"requests": {"cpu": "', self.cpu_request, @@ -100,7 +111,10 @@ struct PodSize(ImplicitlyCopyable, Movable): ) if self.cpu_limit > 0: out.write('"cpu": "', self.cpu_limit, 'm", ') - out.write('"memory": "', self.memory_limit_mb, 'Mi"}}') + out.write('"memory": "', self.memory_limit_mb, 'Mi"') + if gpus > 0: + out.write(', "', GPU_RESOURCE, '": "', gpus, '"') + out.write("}}") return out^ @@ -175,6 +189,49 @@ struct KubeSizes(ImplicitlyCopyable, Movable): ) +@fieldwise_init +struct GroupPods(Copyable, Movable): + """A worker group's pods on Kubernetes (docs/groups.md): `count` dista + workers of the group, each sized `size` and given `gpus` GPUs.""" + + var group: String + var count: Int + var gpus: Int + var size: PodSize + + +def with_groups( + s: KubeSizes, workers: Int, groups: List[GroupPods] +) -> KubeRequests: + """What a run with `workers` workers with no group and `groups`' pods + asks for in all: `s.requests`, with its head when only groups have + workers, and the groups' pods.""" + var out = s.requests(workers) + var grouped = False + for g in groups: + out.cpu_millis += g.count * g.size.cpu_request + out.memory_mb += g.count * g.size.memory_request_mb + grouped = grouped or g.count > 0 + if workers == 0 and grouped: + out.cpu_millis += s.head.cpu_request + out.memory_mb += s.head.memory_request_mb + return out + + +def pod_slugs(groups: List[GroupPods]) -> List[String]: + """Each group's part of its pods' names: its name with `_` as `-` + (a pod's name has no `_`), or `g` where that is another group's.""" + var slugs = List[String]() + for g in groups: + slugs.append(g.group.replace("_", "-")) + for i in range(len(slugs)): + for j in range(len(slugs)): + if i != j and slugs[i] == slugs[j] and groups[i].group != slugs[i]: + slugs[i] = String("g", i) + break + return slugs^ + + def _cpu(request: Request, default: Int, limit: Int) -> Tuple[Int, Int]: if request.cpus_min > 0: return ( diff --git a/src/morca/_internal/provider.mojo b/src/morca/_internal/provider.mojo new file mode 100644 index 00000000..839617cc --- /dev/null +++ b/src/morca/_internal/provider.mojo @@ -0,0 +1,249 @@ +"""One contract for every provider (docs/groups.md): "give run R a worker +of group G, of this size, joined to this head with this token", and "take +it back". A provider is where a placement gets its workers, by name: + +| Provider | Placement | Give | Take back | +|---|---|---|---| +| `pool` | `worker:` | A member's dista worker (`morca._internal.run_cluster`) | Drain, then kill | +| `local` | the local runner | The run's process forks them (`MORCA_WORKERS`, `MORCA_GROUPS`) | The run's end | +| `control` | `control` | The same, `MORCA_CONTROL_WORKERS` with no group | The run's end | +| `kubernetes` | the Kubernetes runner | A worker Pod per worker (`morca._internal.kube`) | The run's end | + +Each builds a dista process's environment here, and nowhere else: the +reserved names `DISTA_ROLE`, `DISTA_HEAD`, `DISTA_ADVERTISE`, +`DISTA_TOKEN`, `DISTA_PORT` and `DISTA_GROUP`, the worker's slots, and its +GPUs (`MORCA_GRANT_GPUS`, `CUDA_VISIBLE_DEVICES`). The `ec2` placement isn't +a provider: it is to be retired and ignores groups +(`morca._internal.groups.placement_warning`). + +- **pool**: a worker is told its head, address, the run's token and slots + (`DISTA_WORKER_SLOTS`: the grant's CPUs, or `auto` when the pipeline's + `env` says so); a member gives up on a head that's gone after + `DISTA_CONNECT_TIMEOUT`. Its GPUs are those its host handed it. +- **local** and **control**: dista forks the head and workers inside the + run's process, so morca gives that process only how many workers to fork, + `MORCA_WORKERS` (control's, `MORCA_CONTROL_WORKERS`; the local runner's + is the scheduler's own, as before) and `MORCA_GROUPS`, each group's + fixed count (`gpu=2,io=1`, morca.tasks). The run's GPUs are the run's + grant, which all its forked workers see. +- **kubernetes**: a worker learns its address from its pod's IP (a + `fieldRef`), and has no token or slots, as before. One of a group gets + `DISTA_GROUP`, and its GPUs are those Kubernetes gives the pod + (`nvidia.com/gpu`), numbered from 0 inside it. +""" + +from morca._internal.json import quote + +comptime POOL = "pool" +comptime LOCAL = "local" +comptime CONTROL_PROVIDER = "control" +comptime KUBERNETES = "kubernetes" + +comptime MEMBER_CONNECT_SECONDS = "10" +"""How long a pool member's dista worker tries a head that's gone.""" +comptime GRANT_GPUS = "MORCA_GRANT_GPUS" +comptime CUDA_DEVICES = "CUDA_VISIBLE_DEVICES" +comptime GROUPS = "MORCA_GROUPS" +"""A local run's groups to fork, `name=count,...` (morca.tasks).""" +comptime POD_IP = "status.podIP" + + +def provider_of(placed: String) raises -> String: + """The provider a run placed at `placed` gets its workers from: `pool` + for `worker:`, else the placement's own name; raises for one that + has none (`ec2`).""" + if placed.startswith("worker:"): + return POOL + if placed == LOCAL or placed == CONTROL_PROVIDER or placed == KUBERNETES: + return placed + raise Error("morca: placement ", placed, " is no provider of workers") + + +@fieldwise_init +struct EnvVar(Copyable, Equatable, Movable): + """One variable of a process: `value`, or on Kubernetes the pod's + field `field` (`status.podIP`).""" + + var name: String + var value: String + var field: String + + def text(self) -> String: + """`NAME=value`, as a spawned process gets it.""" + return String(self.name, "=", self.value) + + def json(self) -> String: + """A container's `env` entry.""" + if self.field: + return String( + '{"name": ', + quote(self.name), + ', "valueFrom": {"fieldRef": {"fieldPath": ', + quote(self.field), + "}}}", + ) + return String( + '{"name": ', quote(self.name), ', "value": ', quote(self.value), "}" + ) + + +def _var(name: String, value: String) -> EnvVar: + return EnvVar(name, value, String()) + + +@fieldwise_init +struct ClusterProcess(Copyable, Movable): + """A dista head or worker of one run's cluster, as a provider starts + it.""" + + var role: String + """`head` or `worker`.""" + var port: Int + """The head's port.""" + var head: String + """A worker's head, `host:port`.""" + var advertise: String + """Where the others reach a worker; empty on Kubernetes (its pod's + IP).""" + var token: String + """The run's cluster token; empty for none (Kubernetes).""" + var slots: String + """`DISTA_WORKER_SLOTS`'s value; empty for none.""" + var member: Bool + """A pool member, which gives up on a head that's gone.""" + var group: String + """The worker's group; empty for the workers with no group.""" + var gpus: Bool + """Whether to say its GPUs (`devices`) at all.""" + var devices: String + """Its GPUs' indexes as `MORCA_GRANT_GPUS` gives them; empty for none.""" + + @staticmethod + def head_at(port: Int, token: String = "") -> ClusterProcess: + return ClusterProcess( + "head", port, "", "", token, "", False, "", False, "" + ) + + @staticmethod + def worker_of( + head: String, + advertise: String = "", + token: String = "", + slots: String = "", + member: Bool = False, + group: String = "", + ) -> ClusterProcess: + return ClusterProcess( + "worker", + 0, + head, + advertise, + token, + slots, + member, + group, + False, + "", + ) + + +def gpu_env(devices: String) -> List[String]: + """A process's GPUs, `devices` (`0,2`, empty for none): it sees those + alone.""" + return [ + String(GRANT_GPUS, "=", devices), + String(CUDA_DEVICES, "=", devices), + ] + + +def pod_devices(gpus: Int) -> String: + """The GPUs a pod given `gpus` sees, numbered from 0: `0,1`.""" + var out = String() + for i in range(gpus): + out.write("," if i else "", i) + return out^ + + +def cluster_env(provider: String, p: ClusterProcess) raises -> List[EnvVar]: + """The variables a provider gives `p`, a head or worker of a run's + cluster. `local` and `control` start none (`local_env`).""" + if provider != POOL and provider != KUBERNETES: + raise Error( + "morca: the ", provider, " provider forks its workers in the run" + ) + var out = List[EnvVar]() + if p.role == "head": + out.append(_var("DISTA_ROLE", "head")) + out.append(_var("DISTA_PORT", String(p.port))) + if p.token: + out.append(_var("DISTA_TOKEN", p.token)) + return out^ + out.append(_var("DISTA_ROLE", "worker")) + out.append(_var("DISTA_HEAD", p.head)) + if provider == KUBERNETES and not p.advertise: + out.append(EnvVar("DISTA_ADVERTISE", String(), String(POD_IP))) + else: + out.append(_var("DISTA_ADVERTISE", p.advertise)) + if p.token: + out.append(_var("DISTA_TOKEN", p.token)) + if p.slots: + out.append(_var("DISTA_WORKER_SLOTS", p.slots)) + if p.member: + out.append(_var("DISTA_CONNECT_TIMEOUT", MEMBER_CONNECT_SECONDS)) + if p.group: + out.append(_var("DISTA_GROUP", p.group)) + if p.gpus: + out.append(_var(GRANT_GPUS, p.devices)) + out.append(_var(CUDA_DEVICES, p.devices)) + return out^ + + +def driver_env( + provider: String, head: String, token: String = "" +) -> List[EnvVar]: + """What a run's driver gets to join its cluster's head at `head`; none + for `local` and `control`, whose driver forks its own.""" + var out = List[EnvVar]() + if (provider == POOL or provider == KUBERNETES) and head: + out.append(_var("DISTA_HEAD", head)) + if token: + out.append(_var("DISTA_TOKEN", token)) + return out^ + + +def local_env(provider: String, workers: Int, groups: String) -> List[String]: + """What a `local` or `control` run's process gets to fork its workers: + `MORCA_WORKERS` for control (`workers`; the local runner's process + inherits the scheduler's), and `MORCA_GROUPS` when it has groups + (`groups`, `name=count,...`).""" + var out = List[String]() + if provider == CONTROL_PROVIDER: + out.append(String("MORCA_WORKERS=", workers)) + if groups and (provider == LOCAL or provider == CONTROL_PROVIDER): + out.append(String(GROUPS, "=", groups)) + return out^ + + +def texts(vars: List[EnvVar]) -> List[String]: + """`vars` as `NAME=value`s, for a spawned process.""" + var out = List[String]() + for v in vars: + out.append(v.text()) + return out^ + + +def json_entries(vars: List[EnvVar]) -> String: + """`vars` as a container's `env` entries, comma-separated.""" + var out = String() + for i in range(len(vars)): + out.write(", " if i else "", vars[i].json()) + return out^ + + +def worker_slots(env: List[String], slots: Int) -> String: + """A pool worker's `DISTA_WORKER_SLOTS`: `auto` if the pipeline's `env` + asks for it, else `slots` (0: one per core).""" + for e in env: + if e == "DISTA_WORKER_SLOTS=auto": + return "auto" + return String(slots) diff --git a/src/morca/_internal/registered.mojo b/src/morca/_internal/registered.mojo index ac19218a..2f05ef59 100644 --- a/src/morca/_internal/registered.mojo +++ b/src/morca/_internal/registered.mojo @@ -29,8 +29,10 @@ from morca._internal.secrets import parse_secrets from morca._internal.kube_size import ( KubeDefaults, KubeRequests, + GroupPods, KubeSizes, kube_sizes, + with_groups, ) from morca._internal.resources import Request from morca._internal.recommend import ( @@ -135,7 +137,11 @@ struct Registered(Copyable, Movable): var groups: List[Group] """Its worker groups in morca.toml (`morca._internal.groups`), by name: on a pool, the members of its runs by group - (`morca._internal.member_wants`).""" + (`morca._internal.member_wants`); on the local runner, the control + host and Kubernetes, its cluster's workers by group + (`morca._internal.provider`).""" + var has_tasks: Bool + """Whether it has dista tasks, and so a cluster to start groups in.""" def request(self) raises -> Request: """As declared: `auto` not resolved (`run_request` does).""" @@ -351,6 +357,7 @@ def registered(mut db: State, only: String = "") raises -> List[Registered]: r.working_set, r.probe_every, parse_groups(r.groups), + r.has_tasks, ) ) # A fixed count, or no tasks: no scaling. @@ -413,11 +420,44 @@ def kube_sizes_of(p: Registered, sized: RunRequest) raises -> KubeSizes: ) +def cluster_groups(p: Registered) -> List[Group]: + """The groups `p`'s cluster starts workers in: its groups if it has + tasks, else none (`morca._internal.provider`).""" + return p.groups.copy() if p.has_tasks else List[Group]() + + +def kube_groups_of(p: Registered, sized: RunRequest) raises -> List[GroupPods]: + """Each of `p`'s groups as pods on Kubernetes: its MAX of them, each + sized from the group's `cpus` and `memory_gb` where it sets them, else + as the pipeline's workers are (`sized`, `auto` resolved), with what an + out-of-memory kill raised the pipeline's memory to, and its GPUs.""" + var out = List[GroupPods]() + for g in cluster_groups(p): + var r = sized.request + var ceiling = p.request().memory_max_mb + if g.cpus: + var own = Request.of(g.cpus, "") + r.cpus_min = own.cpus_min + r.cpus_max = own.cpus_max + if g.memory_gb: + var own = Request.of("", g.memory_gb) + r.memory_min_mb = own.memory_min_mb + r.memory_max_mb = own.memory_max_mb + ceiling = own.memory_max_mb + var size = kube_sizes( + r, ceiling, p.memory_raised_mb, KubeDefaults.from_env() + ).worker + out.append(GroupPods(g.name, g.max_workers, g.gpus, size)) + return out^ + + def _kube_requests(p: Registered) -> Optional[KubeRequests]: - """What a run of `p` asks for on Kubernetes in all, `auto` as last - learned; None if that can't be read.""" + """What a run of `p` asks for on Kubernetes in all, its groups' pods + included, `auto` as last learned; None if that can't be read.""" try: var sized = resolve_request(p.request(), p.learned, p.learn) - return kube_sizes_of(p, sized).requests(p.workers) + return with_groups( + kube_sizes_of(p, sized), p.workers, kube_groups_of(p, sized) + ) except: return None diff --git a/src/morca/_internal/registering.mojo b/src/morca/_internal/registering.mojo index 41fc30da..3f772a9c 100644 --- a/src/morca/_internal/registering.mojo +++ b/src/morca/_internal/registering.mojo @@ -26,7 +26,7 @@ from morca._internal.fill import ( parse_fill_max_runs, ) from morca._common.paths import absolute -from morca._internal.groups import ec2_ignores_groups +from morca._internal.groups import placement_warnings from morca._internal.proc import ( binary_seconds, capture, @@ -260,8 +260,7 @@ def register_pipeline( var twice = repeated_fill(q, now) if twice: print("morca: warning:", twice) - var ignored = ec2_ignores_groups(q.name, q.placement, q.groups) - if ignored: + for ignored in placement_warnings(q.name, q.placement, q.groups): print("morca: warning:", ignored, file=stderr) if q.fill.all and q.fill.budget < 0: print( diff --git a/src/morca/_internal/resources.mojo b/src/morca/_internal/resources.mojo index e82ac3dc..a87127b0 100644 --- a/src/morca/_internal/resources.mojo +++ b/src/morca/_internal/resources.mojo @@ -49,15 +49,18 @@ without a grant takes a slot per core. (`host_gpus`) and says how many with each claim. A request's `gpus` are whole and granted exactly, never as a range; admission decides how many a start holds, and the worker picks which free devices (`Gpus`) and passes -them as `MORCA_GRANT_GPUS` and `CUDA_VISIBLE_DEVICES`. Only a group asks -for GPUs (`morca._internal.groups`), so until members by group land no -run's request does. +them as `MORCA_GRANT_GPUS` and `CUDA_VISIBLE_DEVICES` +(`morca._internal.provider.gpu_env`). Only a group asks for GPUs +(`morca._internal.groups`): on a pool its member's request, and on the +local runner and the control host the run's, whose GPUs the scheduler's +host hands out the same way (`local_gpus`). """ from std.os import getenv from std.sys.info import CompilationTarget, num_logical_cores from morca._internal.proc import capture +from morca._internal.provider import gpu_env from morca._internal.sample import _read, _sysctl_u64, parse_meminfo comptime MAX_CPUS = 1024 @@ -68,7 +71,6 @@ comptime WAITING = "waiting: needs " comptime GRANT_CPUS = "MORCA_GRANT_CPUS" comptime GRANT_MEMORY_MB = "MORCA_GRANT_MEMORY_MB" comptime GRANT_GPUS = "MORCA_GRANT_GPUS" -comptime CUDA_DEVICES = "CUDA_VISIBLE_DEVICES" comptime HOST_GPUS = "MORCA_HOST_GPUS" comptime GPU_COUNT_SECONDS = 10.0 """How long `host_gpus` waits for `nvidia-smi`.""" @@ -421,8 +423,7 @@ struct Grant(ImplicitlyCopyable, Movable): if self.memory_mb > 0: out.append(String(GRANT_MEMORY_MB, "=", self.memory_mb)) if host_gpus > 0 or self.gpus > 0 or self.devices: - out.append(String(GRANT_GPUS, "=", self.devices)) - out.append(String(CUDA_DEVICES, "=", self.devices)) + out.extend(gpu_env(self.devices)) return out^ diff --git a/src/morca/_internal/scheduler.mojo b/src/morca/_internal/scheduler.mojo index 846da2fb..cad1499f 100644 --- a/src/morca/_internal/scheduler.mojo +++ b/src/morca/_internal/scheduler.mojo @@ -228,8 +228,11 @@ from morca._internal.sample import ( tree_usage, ) from morca._internal.resources import ( + Gpus, Grant, Room, + devices_text, + host_gpus, host_room, ) from morca._internal.admission import ( @@ -374,6 +377,14 @@ struct Scheduler(Movable): var room: Room """What this host can grant the runs of pipelines with a request (`morca._internal.resources`): its capacity less its reserve.""" + var gpus: Gpus + """This host's GPUs, as its local and control-placed runs hold them + (docs/groups.md): counted (`host_gpus`) the first time a run asks for + some, none until then.""" + var gpus_counted: Bool + var _holding: Dict[Int, List[Int]] + """A local or control-placed run's process to the GPUs it holds, given + back when it's reaped.""" var _control: Dict[Int, _ControlProc] """A control-placed run's process to what its end needs.""" var _kept: Dict[Int, _ControlProc] @@ -492,6 +503,9 @@ struct Scheduler(Movable): self._kept = Dict[Int, _ControlProc]() self._keeping = Dict[Int, String]() self._meters = Dict[Int, Meter]() + self.gpus = Gpus(0) + self.gpus_counted = False + self._holding = Dict[Int, List[Int]]() self.psi = find_source() self.admission = Admission.from_env() self._pressure_kept = 0 @@ -757,6 +771,43 @@ struct Scheduler(Movable): left.append(path) self._unswept = left^ + def gpu_room(mut self) -> Room: + """This host's room with its GPUs, counted now if they weren't + (`MORCA_HOST_GPUS`, else `nvidia-smi`); a bad `MORCA_HOST_GPUS` + is said and counts none.""" + if not self.gpus_counted: + self.gpus_counted = True + try: + self.gpus = Gpus(host_gpus()) + except e: + print("morca: no GPUs counted on this host:", e) + if self.gpus.count() > 0: + print("morca: this host has", self.gpus.count(), "GPUs") + var room = self.room + room.gpus = self.gpus.count() + room.free_gpus = self.gpus.free() + return room + + def take_gpus(mut self, var grant: Grant) raises -> Grant: + """`grant` with the devices of its GPUs, now held; as it is for + none.""" + if grant.gpus > 0: + grant.devices = devices_text(self.gpus.take(grant.gpus)) + return grant + + def hold_gpus(mut self, pid: Int, grant: Grant): + """`pid` holds `grant`'s devices until it's reaped.""" + if grant.devices: + self._holding[pid] = grant.device_list() + + def give_back_gpus(mut self, pid: Int): + """The GPUs `pid` held are free again.""" + if pid in self._holding: + try: + self.gpus.give_back(self._holding.pop(pid)) + except: + pass + def _contain( mut self, p: Registered, diff --git a/src/morca/_internal/secrets.mojo b/src/morca/_internal/secrets.mojo index f1dbd911..e57a3b6a 100644 --- a/src/morca/_internal/secrets.mojo +++ b/src/morca/_internal/secrets.mojo @@ -99,6 +99,7 @@ comptime _RESERVED_ENV = [ "MORCA_IMAGE", "MORCA_SECRETS", "MORCA_WORKERS", + "MORCA_GROUPS", "DISTA_ROLE", "DISTA_HEAD", "DISTA_ADVERTISE", diff --git a/src/morca/_internal/starting.mojo b/src/morca/_internal/starting.mojo index f9a72e68..32f1d803 100644 --- a/src/morca/_internal/starting.mojo +++ b/src/morca/_internal/starting.mojo @@ -34,7 +34,9 @@ from morca._internal.key_wait import key_room, started from morca._internal.kube import ( RunSpec, ) -from morca._internal.kube_size import KubeSizes +from morca._internal.kube_size import GroupPods, KubeSizes, with_groups +from morca._internal.groups import Group, local_gpus, local_groups +from morca._internal.provider import LOCAL, local_env from morca._internal.logs import ( is_remote, run_dir, @@ -67,6 +69,8 @@ from morca._internal.scheduler import ( from morca._internal.registered import ( Registered, _ec2_spec, + cluster_groups, + kube_groups_of, fill_pipeline, kube_sizes_of, recorded_cpus, @@ -229,11 +233,14 @@ def _start( var need = 0 var pod_memory = 0 var pod_sizes = KubeSizes.none() + var pod_groups = List[GroupPods]() if control: need = 0 # no instance: nothing of the budget elif self.runner: pod_sizes = kube_sizes_of(p, sized) - var asks = pod_sizes.requests(p.workers) + # Its groups' pods too (docs/groups.md, morca._internal.provider). + pod_groups = kube_groups_of(p, sized) + var asks = with_groups(pod_sizes, p.workers, pod_groups) need = asks.cpu_millis # Its pods' memory, to price it (morca._internal.kube_price). pod_memory = asks.memory_mb @@ -277,6 +284,11 @@ def _start( # minimum fits what the running runs weren't granted, each with its # grant. A pipeline without one is started as ever. var request = sized.request + # A run that forks its groups' workers here holds their GPUs, each + # group's for each of its MAX workers (docs/groups.md). + var groups = cluster_groups(p) + if local: + request.gpus = local_gpus(groups) if request.memory_min_mb > 0: # At least what an out-of-memory kill raised it to. request.memory_min_mb = raised_request( @@ -305,7 +317,8 @@ def _start( # Across pipelines: one start at a time weighs the grants. starting_db.xact_lock(tx, _HOST_LOCK) var g = starting_db.granted(tx, self.stale, self._dead("$1")) - var got = admit(request, self.room, g[0], g[1], free) + var room = self.gpu_room() if request.gpus > 0 else self.room + var got = admit(request, room, g[0], g[1], free) grants = got[0].copy() if len(grants) < free: # The ones that don't start say why; those that do, not. @@ -392,6 +405,7 @@ def _start( self.instance if local else 0, sized.source, sized.runs, + grant.gpus, ) ) if pod_memory > 0: @@ -418,6 +432,7 @@ def _start( "CPUs and", grant.memory_mb, "MB (0: not asked for)", + String("and ", grant.gpus, " GPUs") if grant.gpus else String(), sized.text(), String( "(", sized.cap_text(), ")" @@ -426,7 +441,9 @@ def _start( elif sized.source == DEFAULT: print("run", id, "of", p.name, "requests", sized.text()) if control: - _start_control(self, p, Int(id), starts[i], new_code[i], grant) + _start_control( + self, p, Int(id), starts[i], new_code[i], grant, groups + ) continue if self.runner: try: @@ -447,6 +464,7 @@ def _start( p.env.copy(), secrets^, pod_sizes, + pod_groups.copy(), ) ) print("started", p.name, "run", id, "on its cluster") @@ -472,7 +490,18 @@ def _start( # Its own variables, from morca.toml, its grant # (morca.resources), and its secrets, read now and named in # MORCA_SECRETS for masking; the rest it inherits. - var env = grant_env(p.env, grant, pressure_env(self.psi)) + try: + # Its GPUs, held until its process is reaped. + grant = self.take_gpus(grant) + except e: + print("morca: run", id, "of", p.name, "can't start:", e) + starting_db.fail_start(self.db.conn, id, String("can't start: ", e)) + continue + # How many workers its process forks, by group, as the local + # provider gives it (morca._internal.provider). + var extra = local_env(LOCAL, 0, local_groups(groups)) + extra.extend(pressure_env(self.psi)) + var env = grant_env(p.env, grant, extra) try: var secrets = List[Tuple[String, String]]() for s in p.secrets: @@ -481,6 +510,7 @@ def _start( except e: # Retried as a run whose process failed is. print("morca: run", id, "of", p.name, "can't start:", e) + self.gpus.give_back(grant.device_list()) starting_db.fail_start(self.db.conn, id, String("can't start: ", e)) continue var log = String() @@ -513,13 +543,19 @@ def _start( with open(stage, "a") as f: f.write("--- start ", starts[i], "\n") var cg = self._contain(p, Int(id), starts[i], grant, False) - var pid = spawn( - argv, - stage, - env=env, - nice=self.cgroups.nice_for(cg.path), - cgroup=cg.path, - ) + var pid: Int + try: + pid = spawn( + argv, + stage, + env=env, + nice=self.cgroups.nice_for(cg.path), + cgroup=cg.path, + ) + except e: + self.gpus.give_back(grant.device_list()) + raise e^ + self.hold_gpus(pid, grant) if cg.path: if probed(Int(id), starts[i], _probe_every(p)): self._probe.watch(pid, cg) @@ -563,7 +599,8 @@ def _start_control( id: Int, start: Int, new_code: Bool, - grant: Grant = Grant.none(), + var grant: Grant = Grant.none(), + groups: List[Group] = List[Group](), ): """Starts start `start` of `p`'s run `id` on this host (`morca._internal.control`): its binary's `resume`, in a process group of its @@ -573,12 +610,24 @@ def _start_control( run whose process failed is.""" var c: _ControlProc var pid: Int + try: + # Its GPUs, held until its process is reaped. + grant = self.take_gpus(grant) + except e: + print("morca: run", id, "of", p.name, "can't start:", e) + try: + starting_db.fail_start( + self.db.conn, Int64(id), String("can't start: ", e) + ) + except e2: + print("morca: can't record run", id, "failing:", e2) + return var cg = self._contain(p, id, start, grant, True) try: var secrets = List[Tuple[String, String]]() for s in p.secrets: secrets.append((s[0], fetch_secret(s[1]))) - var extra = run_env(self.limits, p.image, secrets) + var extra = run_env(self.limits, p.image, secrets, local_groups(groups)) extra.extend(pressure_env(self.psi)) var env = grant_env(p.env, grant, extra) var location = String() @@ -607,6 +656,7 @@ def _start_control( c = _ControlProc(id, p.binary, stage, location, start, env^, "") except e: print("morca: run", id, "of", p.name, "can't start:", e) + self.gpus.give_back(grant.device_list()) if cg.path and not Cgroups.remove(cg.path): self._unswept.append(cg.path) try: @@ -617,6 +667,7 @@ def _start_control( print("morca: can't record run", id, "failing:", e2) return self._spawned[pid] = (id, start, c.stage) + self.hold_gpus(pid, grant) self._meters[pid] = Meter() if cg.path: if probed(id, start, _probe_every(p)): diff --git a/src/morca/_internal/tick.mojo b/src/morca/_internal/tick.mojo index 1b18524b..d4d59d06 100644 --- a/src/morca/_internal/tick.mojo +++ b/src/morca/_internal/tick.mojo @@ -53,6 +53,7 @@ def tick(mut self: Scheduler, now: Int64) raises: continue print("reaped pid", done.pid, "exit", done.code) var spawned = self._spawned.pop(done.pid, (-1, 0, String())) + self.give_back_gpus(done.pid) var over = String() var ctl = Optional[_ControlProc](None) if done.pid in self._control: diff --git a/src/morca/_internal/worker.mojo b/src/morca/_internal/worker.mojo index b676cdcc..537d42b2 100644 --- a/src/morca/_internal/worker.mojo +++ b/src/morca/_internal/worker.mojo @@ -87,6 +87,7 @@ from morca._internal.member_drain import MemberDrains from morca._internal.run_cluster import MemberSpec, member_spec_of from morca._internal.tokens import new_token from morca._internal.worker_demand import DemandReports, head_status +from morca._internal.provider import POOL, driver_env, texts from morca._internal.worker_cluster import ( free_port, start_dista_worker, @@ -405,8 +406,11 @@ struct Worker(Movable): False, ) ) - env.append(String("DISTA_HEAD=127.0.0.1:", port)) - env.append(String("DISTA_TOKEN=", cluster_token)) + env.extend( + texts( + driver_env(POOL, String("127.0.0.1:", port), cluster_token) + ) + ) cluster_head = String(self.advertise, ":", port) var argv: List[String] = [spec.binary, "resume", String(spec.run)] if spec.allow_new_code: diff --git a/src/morca/_internal/worker_cluster.mojo b/src/morca/_internal/worker_cluster.mojo index 864282b0..12d7dcbc 100644 --- a/src/morca/_internal/worker_cluster.mojo +++ b/src/morca/_internal/worker_cluster.mojo @@ -14,8 +14,13 @@ from std.ffi import c_int, external_call from dista.socket import Listener from morca._internal.proc import spawn - -comptime MEMBER_CONNECT_SECONDS = "10" +from morca._internal.provider import ( + POOL, + ClusterProcess, + cluster_env, + texts, + worker_slots as slots_of, +) def free_port() raises -> Int: @@ -35,17 +40,14 @@ def _with(var env: List[String], extra: List[String]) -> List[String]: def start_head( binary: String, env: List[String], log: String, port: Int, token: String ) raises -> Int: - """The run's dista head, on `port`; its pid (its own process group).""" + """The run's dista head, on `port`; its pid (its own process group). + Its variables are the pool provider's (`morca._internal.provider`).""" return spawn( [binary], log, env=_with( env.copy(), - [ - String("DISTA_ROLE=head"), - String("DISTA_PORT=", port), - String("DISTA_TOKEN=", token), - ], + texts(cluster_env(POOL, ClusterProcess.head_at(port, token))), ), group=True, ) @@ -54,10 +56,7 @@ def start_head( def worker_slots(env: List[String], slots: Int) -> String: """A cluster worker's `DISTA_WORKER_SLOTS=`: `auto` if `env` asks for it, else `slots`.""" - for e in env: - if e == "DISTA_WORKER_SLOTS=auto": - return String("DISTA_WORKER_SLOTS=auto") - return String("DISTA_WORKER_SLOTS=", slots) + return String("DISTA_WORKER_SLOTS=", slots_of(env, slots)) def start_dista_worker( @@ -77,19 +76,18 @@ def start_dista_worker( all of it its own); its pid. A member's gives up on a head that's gone within `MEMBER_CONNECT_SECONDS`. One of a worker group (docs/groups.md) gets `DISTA_GROUP`, so the head sends it that group's tasks alone; one - with none runs the tasks that name no group.""" - var extra: List[String] = [ - String("DISTA_ROLE=worker"), - String("DISTA_HEAD=", head), - String("DISTA_ADVERTISE=", advertise), - String("DISTA_TOKEN=", token), - worker_slots(env, slots), - ] - if member: - extra.append(String("DISTA_CONNECT_TIMEOUT=", MEMBER_CONNECT_SECONDS)) - if group: - extra.append(String("DISTA_GROUP=", group)) - return spawn([binary], log, env=_with(env.copy(), extra), group=True) + with none runs the tasks that name no group. Its variables are the + pool provider's (`morca._internal.provider`); its GPUs are in `env`, + from its grant.""" + var p = ClusterProcess.worker_of( + head, advertise, token, slots_of(env, slots), member, group + ) + return spawn( + [binary], + log, + env=_with(env.copy(), texts(cluster_env(POOL, p))), + group=True, + ) def stop_group(pid: Int): diff --git a/src/morca/tasks.mojo b/src/morca/tasks.mojo index e6145b9b..97aaf730 100644 --- a/src/morca/tasks.mojo +++ b/src/morca/tasks.mojo @@ -13,8 +13,10 @@ def load(mut ctx: Ctx, raw: RawFile) raises -> Loaded: A run of a pipeline with tasks starts one dista `Runtime` before its first step and keeps it until the run ends: in local mode it forks a head and -`MORCA_WORKERS` workers (default 4); with `DISTA_HEAD` set it joins that -cluster instead. The same binary is dista's worker: run with `DISTA_ROLE` +`MORCA_WORKERS` workers (default 4) with no group, and the workers of each +group `MORCA_GROUPS` names (`gpu=1,io=2`, which the local runner and the +control host set from the pipeline's groups, docs/groups.md); with +`DISTA_HEAD` set it joins that cluster instead. The same binary is dista's worker: run with `DISTA_ROLE` set, `morca_main` hands the process to dista before reading its arguments. The runtime starts before morca opens a database connection or its heartbeat @@ -173,7 +175,7 @@ struct Tasks[*Ts: TaskLike](TaskSet): comptime if CompilationTarget.is_macos(): if not head and not getenv("DISTA_ROLE"): init_curl_before_fork() - return Self.RT(workers=workers) + return Self.RT(workers=workers, groups=getenv("MORCA_GROUPS")) @staticmethod def names() -> List[String]: diff --git a/tests/grants.sh b/tests/grants.sh index e03b8aa5..bf0c35c3 100755 --- a/tests/grants.sh +++ b/tests/grants.sh @@ -24,7 +24,13 @@ # is granted none, its process sees none (MORCA_GRANT_GPUS and # CUDA_VISIBLE_DEVICES empty) and nothing else changes; on hosts without # GPUs neither variable is set; a bad MORCA_HOST_GPUS stops the worker at -# start. +# start; +# - worker groups on the local runner and the control host (docs/groups.md): +# gpufan (tests/run_cluster/gpufan.mojo) with groups gpu ("1..2", a GPU +# each) and io waits while the host has fewer GPUs than its groups' MAX +# ask for, then forks each group's MAX beside its workers with no group: +# its model tasks run only in group gpu, its plain ones only in no group, +# and every worker of the run sees the run's GPUs. # # Needs MORCA_DATABASE_URL (pixi run test-grants starts a throwaway server), # curl and jq. @@ -32,7 +38,7 @@ set -eu cd "$(dirname "$0")/.." . "$PWD/tests/port.sh" mkdir -p build -scripts/pipelines.sh wide narrow plain +scripts/pipelines.sh wide narrow plain gpufan # shellcheck disable=SC2086 scripts/mojo-build.sh -I src $DEP_INC bin/scheduler.mojo -o build/morca log=build/grants.log @@ -323,6 +329,65 @@ q "UPDATE orca.pipelines SET fills = NULL WHERE name = 'narrow'" > /dev/null ./build/morca register --config build/grants.toml ./build/narrow >> "$log" 2>&1 || fail "register narrow back" echo "ok fill_max_runs = \"auto\" runs as many fill runs at once as fit (4 of 2 GB in 8 GB)" +# Worker groups on the local runner and the control host (docs/groups.md). +gf=$PWD/build/grants-gpufan +cat > build/grants-gpufan.toml << 'EOF' +[pipelines.gpufan] + +[pipelines.gpufan.groups.gpu] +workers = "1..2" +gpus = 1 + +[pipelines.gpufan.groups.io] +workers = 1 +EOF +./build/morca register --config build/grants-gpufan.toml ./build/gpufan >> "$log" 2>&1 || fail "register gpufan" +export GPUFAN_OUT="$gf" GPUFAN_SLEEP=0.2 MORCA_HOST_GPUS=1 +start_sched +./build/morca backfill gpufan 2024-01 >> "$log" 2>&1 || fail "backfill gpufan" +g1=$(q "SELECT max(id) FROM orca.runs") +want="waiting: needs 2 GPUs, more than the 1 this host grants at most" +until_ 20 "gpufan's run wasn't held for GPUs: $(q "SELECT status, held FROM orca.runs WHERE id = $g1")" \ + is "SELECT status || ' ' || held FROM orca.runs WHERE id = $g1" "queued $want" +stop_sched +echo "ok a run whose groups ask for more GPUs than the host has waits, saying so" +# groups_ran RUN PLACEMENT DEVICES: RUN succeeded at PLACEMENT holding +# DEVICES, its model tasks in group gpu alone and its plain ones in no group. +groups_ran() { + until_ 60 "gpufan's run $1 didn't succeed: $(q "SELECT status, error, held FROM orca.runs WHERE id = $1")" \ + is "SELECT status FROM orca.runs WHERE id = $1" succeeded + is "SELECT placement || ' ' || grant_gpus FROM orca.runs WHERE id = $1" "$2 2" \ + || fail "gpufan's run $1: $(q "SELECT placement, grant_gpus FROM orca.runs WHERE id = $1")" + n=$(find "$gf" -name 'model-*.env' | wc -l | tr -d ' ') + { [ "$n" -ge 1 ] && [ "$n" -le 2 ]; } || fail "model tasks ran in $n workers: $(ls "$gf")" + [ "$(find "$gf" -name 'plain-*.env' | wc -l | tr -d ' ')" -eq 1 ] || fail "plain tasks ran in: $(ls "$gf")" + for f in "$gf"/model-*.env; do + grep -qx "DISTA_GROUP=gpu" "$f" || fail "$f: $(cat "$f")" + grep -qx "CUDA_VISIBLE_DEVICES=$3" "$f" || fail "$f: $(cat "$f")" + grep -qx "MORCA_GRANT_GPUS=$3" "$f" || fail "$f: $(cat "$f")" + done + for f in "$gf"/plain-*.env; do + grep -qx "DISTA_GROUP=-" "$f" || fail "$f: $(cat "$f")" + grep -qx "CUDA_VISIBLE_DEVICES=$3" "$f" || fail "$f: $(cat "$f")" + done +} +rm -rf "$gf" +mkdir -p "$gf" +export MORCA_HOST_GPUS=3 +start_sched +groups_ran "$g1" local 0,1 +echo "ok a local run forks each group's MAX, which runs that group's tasks alone, with the run's GPUs" +./build/morca register --config build/grants-gpufan.toml --placement control ./build/gpufan >> "$log" 2>&1 \ + || fail "register gpufan on control" +rm -rf "$gf" +mkdir -p "$gf" +./build/morca backfill gpufan 2024-02 >> "$log" 2>&1 || fail "backfill gpufan" +g2=$(q "SELECT max(id) FROM orca.runs") +groups_ran "$g2" control 0,1 +stop_sched +unset MORCA_HOST_GPUS GPUFAN_OUT GPUFAN_SLEEP +echo "ok so does a control-placed run" + # On a remote worker, against its own host. export MORCA_HOST_MEMORY_MB=8192 ./build/morca register --config build/grants.toml --placement worker:g ./build/wide >> "$log" 2>&1 || fail "register wide on a worker" diff --git a/tests/test_control.mojo b/tests/test_control.mojo index dfc99233..53581c11 100644 --- a/tests/test_control.mojo +++ b/tests/test_control.mojo @@ -126,6 +126,10 @@ def test_run_env() raises: assert_equal(e[2], "GITHUB_TOKEN=tok") assert_equal(e[3], "API_KEY=key") assert_equal(e[4], "MORCA_SECRETS=GITHUB_TOKEN,API_KEY") + # Its groups' workers, forked beside its own (docs/groups.md). + var g = run_env(l, "", List[Tuple[String, String]](), "gpu=1") + assert_equal(len(g), 2) + assert_equal(g[1], "MORCA_GROUPS=gpu=1") def test_stage() raises: diff --git a/tests/test_groups.mojo b/tests/test_groups.mojo index 58e3e46a..676cfb81 100644 --- a/tests/test_groups.mojo +++ b/tests/test_groups.mojo @@ -25,6 +25,9 @@ from morca._internal.groups import ( Group, ec2_ignores_groups, group_name_problem, + local_gpus, + local_groups, + placement_warnings, groups_json, parse_groups, ) @@ -290,8 +293,44 @@ def test_ec2_ignores_groups() raises: assert_equal(ec2_ignores_groups("b", "control", f.groups("b")), "") +def test_control_ignores_a_groups_sizes() raises: + """On the control host a run is granted as one: its groups' cpus and + memory_gb are said to be ignored, their workers and GPUs aren't.""" + var sized: List[Group] = [ + Group("gpu", 1, 1, 1, "", "16"), + Group("io", 2, 2, 0, "", ""), + ] + var w = placement_warnings("p", "control", sized) + assert_equal(len(w), 1) + assert_true("ignores the cpus and memory_gb of its groups (gpu)" in w[0]) + assert_equal(len(placement_warnings("p", "", sized)), 0) + assert_equal(len(placement_warnings("p", "worker:batch", sized)), 0) + var e = placement_warnings("p", "ec2", sized) + assert_equal(len(e), 1) + assert_true("place it on a pool" in e[0]) + + +def test_local_groups() raises: + """What a run that forks its workers is told to fork, and the GPUs it + asks for: each group's MAX.""" + assert_equal(local_groups(List[Group]()), "") + assert_equal(local_gpus(List[Group]()), 0) + var g: List[Group] = [ + Group("io", 1, 1, 0, "", ""), + Group("gpu", 0, 2, 1, "4", "16"), + ] + assert_equal(local_groups(g), "gpu=2,io=1") + assert_equal(local_gpus(g), 2) + + def test_dista_names_are_reserved() raises: - for n in ["DISTA_TOKEN", "DISTA_PORT", "DISTA_GROUP", "DISTA_ROLE"]: + for n in [ + "DISTA_TOKEN", + "DISTA_PORT", + "DISTA_GROUP", + "DISTA_ROLE", + "MORCA_GROUPS", + ]: assert_true("is set by morca itself" in env_name_problem(String(n))) # A pipeline sets this one (docs/morca-toml.md, "auto" from the grant). assert_equal(env_name_problem("DISTA_WORKER_SLOTS"), "") diff --git a/tests/test_kube.mojo b/tests/test_kube.mojo index 5e25b600..7ec87663 100644 --- a/tests/test_kube.mojo +++ b/tests/test_kube.mojo @@ -4,7 +4,9 @@ settings, with the S3 keys from the stack's Secret, never as values; and their sizes, from the pipeline's request, with limits, and what a pod killed for its memory says (morca._internal.kube_size); where they go, pull secrets, node selectors, tolerations, anti-affinity and a priority class -(morca._internal.kube_place), and why a pod can't start. +(morca._internal.kube_place), and why a pod can't start; and the head's +and workers' own variables, a worker group's pods, their GPUs and what they +ask for in all (docs/groups.md, morca._internal.provider). tests/kind.sh runs it on a cluster. """ @@ -17,9 +19,12 @@ from morca._internal.kube import pod_env, s3_key_env, secret_env, secret_name from morca._internal.kube_size import ( EVICTED, OOM_KILLED, + GroupPods, KubeDefaults, Killed, PodSize, + pod_slugs, + with_groups, killed_text, kube_sizes, next_memory_mb, @@ -30,6 +35,14 @@ from morca._internal.kube_size import ( ) from morca._internal.kube_place import KubePlacement, Toleration from morca._internal.logs import mask_values +from morca._internal.provider import ( + KUBERNETES, + ClusterProcess, + cluster_env, + driver_env, + json_entries, + pod_devices, +) from morca._internal.resources import Request @@ -479,5 +492,100 @@ def test_pod_stuck() raises: assert_true(t.byte_length() < 400, t) +def test_cluster_pods_env_is_as_before() raises: + """The kubernetes provider gives the head and the workers with no group + what they had before it named the contract.""" + assert_equal( + json_entries(cluster_env(KUBERNETES, ClusterProcess.head_at(6390))), + ( + '{"name": "DISTA_ROLE", "value": "head"}, {"name":' + ' "DISTA_PORT", "value": "6390"}' + ), + ) + assert_equal( + json_entries( + cluster_env( + KUBERNETES, ClusterProcess.worker_of("morca-1-1-head:6390") + ) + ), + ( + '{"name": "DISTA_ROLE", "value": "worker"}, {"name":' + ' "DISTA_HEAD", "value": "morca-1-1-head:6390"}, {"name":' + ' "DISTA_ADVERTISE", "valueFrom": {"fieldRef": {"fieldPath":' + ' "status.podIP"}}}' + ), + ) + var d = driver_env(KUBERNETES, "morca-1-1-head:6390") + assert_equal(len(d), 1) + assert_equal(d[0].text(), "DISTA_HEAD=morca-1-1-head:6390") + assert_equal(len(driver_env(KUBERNETES, "")), 0) + + +def test_a_group_pods_env() raises: + """A group's worker gets DISTA_GROUP and the GPUs it sees, from 0.""" + var p = ClusterProcess.worker_of("h:6390", group="gpu") + p.gpus = True + p.devices = pod_devices(2) + var env = loads(String("[", json_entries(cluster_env(KUBERNETES, p)), "]")) + var got = Dict[String, String]() + for e in env.array_items(): + var v = e.get("value") + got[ + e["name"].string_value() + ] = v.value().string_value() if v else String("") + assert_equal(got["DISTA_GROUP"], "gpu") + assert_equal(got["MORCA_GRANT_GPUS"], "0,1") + assert_equal(got["CUDA_VISIBLE_DEVICES"], "0,1") + assert_equal(got["DISTA_ADVERTISE"], "") + assert_false("DISTA_TOKEN" in got) + # A group without GPUs sees none. + p.devices = pod_devices(0) + var none = loads(String("[", json_entries(cluster_env(KUBERNETES, p)), "]")) + for e in none.array_items(): + if e["name"].string_value() == "CUDA_VISIBLE_DEVICES": + assert_equal(e["value"].string_value(), "") + + +def test_a_groups_gpus_are_limits() raises: + var s = PodSize(1000, 2000, 1024, 2048) + var gpu = loads(s.resources(1)).at("/limits").get("nvidia.com/gpu") + assert_true(Bool(gpu)) + assert_equal(gpu.value().string_value(), "1") + assert_false(Bool(loads(s.resources()).at("/limits").get("nvidia.com/gpu"))) + assert_equal(s.resources(), s.resources(0)) + + +def test_group_pods_are_counted_with_the_run() raises: + var d = KubeDefaults(500, 250, 1000, 2000, 512) + var sizes = kube_sizes(Request(0, 0, 0, 0), 0, 0, d) + var g: List[GroupPods] = [ + GroupPods("gpu", 2, 1, PodSize(4000, 4000, 16384, 16384)), + GroupPods("io", 0, 0, PodSize(1000, 2000, 512, 512)), + ] + var plain = with_groups(sizes, 2, List[GroupPods]()) + assert_equal(plain.cpu_millis, sizes.requests(2).cpu_millis) + var both = with_groups(sizes, 2, g) + assert_equal(both.cpu_millis, sizes.requests(2).cpu_millis + 8000) + assert_equal(both.memory_mb, sizes.requests(2).memory_mb + 32768) + # Only groups have workers: the head is counted too. + var only = with_groups(sizes, 0, g) + assert_equal(only.cpu_millis, 500 + 250 + 8000) + # No worker at all: the driver alone, as before. + assert_equal(with_groups(sizes, 0, List[GroupPods]()).cpu_millis, 500) + + +def test_group_pod_names() raises: + var z = PodSize(0, 0, 0, 0) + var g: List[GroupPods] = [ + GroupPods("a-b", 1, 0, z), + GroupPods("a_b", 1, 0, z), + GroupPods("gpu_big", 1, 0, z), + ] + var slugs = pod_slugs(g) + assert_equal(slugs[0], "a-b") + assert_equal(slugs[1], "g1") + assert_equal(slugs[2], "gpu-big") + + def main() raises: TestSuite.discover_tests[__functions_in_module()]().run() diff --git a/tests/test_resources.mojo b/tests/test_resources.mojo index 70957faa..c853f3ea 100644 --- a/tests/test_resources.mojo +++ b/tests/test_resources.mojo @@ -31,6 +31,18 @@ from morca._internal.resources import ( parse_memory_gb, run_env, ) +from morca._internal.provider import ( + CONTROL_PROVIDER, + KUBERNETES, + LOCAL, + POOL, + ClusterProcess, + cluster_env, + driver_env, + local_env, + provider_of, + texts, +) from morca._internal.worker_cluster import worker_slots @@ -217,6 +229,74 @@ def test_worker_slots() raises: assert_equal(worker_slots(List[String](), 0), "DISTA_WORKER_SLOTS=0") +def test_providers_by_name() raises: + """Each placement's provider, by its name; ec2 has none.""" + assert_equal(provider_of("worker:batch"), POOL) + assert_equal(provider_of("local"), LOCAL) + assert_equal(provider_of("control"), CONTROL_PROVIDER) + assert_equal(provider_of("kubernetes"), KUBERNETES) + with assert_raises(contains="no provider"): + _ = provider_of("ec2") + + +def test_pool_cluster_env_is_as_before() raises: + """A pool's head and workers get what start_head and start_dista_worker + gave them before the contract had a name, in that order.""" + var head = texts(cluster_env(POOL, ClusterProcess.head_at(4100, "tok"))) + assert_equal(len(head), 3) + assert_equal(head[0], "DISTA_ROLE=head") + assert_equal(head[1], "DISTA_PORT=4100") + assert_equal(head[2], "DISTA_TOKEN=tok") + var own = texts( + cluster_env( + POOL, + ClusterProcess.worker_of("127.0.0.1:4100", "10.0.0.2", "tok", "3"), + ) + ) + var want: List[String] = [ + "DISTA_ROLE=worker", + "DISTA_HEAD=127.0.0.1:4100", + "DISTA_ADVERTISE=10.0.0.2", + "DISTA_TOKEN=tok", + "DISTA_WORKER_SLOTS=3", + ] + assert_equal(len(own), len(want)) + for i in range(len(want)): + assert_equal(own[i], want[i]) + var member = texts( + cluster_env( + POOL, + ClusterProcess.worker_of( + "10.0.0.1:4100", "10.0.0.2", "tok", "auto", True, "gpu" + ), + ) + ) + assert_equal(len(member), 7) + assert_equal(member[4], "DISTA_WORKER_SLOTS=auto") + assert_equal(member[5], "DISTA_CONNECT_TIMEOUT=10") + assert_equal(member[6], "DISTA_GROUP=gpu") + var d = texts(driver_env(POOL, "127.0.0.1:4100", "tok")) + assert_equal(len(d), 2) + assert_equal(d[1], "DISTA_TOKEN=tok") + + +def test_local_providers_fork_their_workers() raises: + """local and control start no dista process: their run's process forks + its workers, by group.""" + with assert_raises(contains="forks its workers"): + _ = cluster_env(LOCAL, ClusterProcess.head_at(1)) + assert_equal(len(local_env(LOCAL, 0, "")), 0) + var l = local_env(LOCAL, 0, "gpu=2,io=1") + assert_equal(len(l), 1) + assert_equal(l[0], "MORCA_GROUPS=gpu=2,io=1") + var c = local_env(CONTROL_PROVIDER, 1, "") + assert_equal(len(c), 1) + assert_equal(c[0], "MORCA_WORKERS=1") + assert_equal(len(local_env(CONTROL_PROVIDER, 1, "gpu=1")), 2) + assert_equal(len(local_env(KUBERNETES, 1, "gpu=1")), 0) + assert_equal(len(driver_env(LOCAL, "h:1")), 0) + + def test_auto_count() raises: _ = unsetenv("MORCA_TEST_PARALLEL") assert_equal(auto_count("MORCA_TEST_PARALLEL", 16), 16)