mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(sagemaker): support GPU-backed training jobs (#4015)
* feat(sagemaker): support GPU-backed training jobs ResourceConfig.InstanceType had no effect on the container Floci launched, so a training job asking for ml.g5.xlarge ran on CPU. This maps the accelerator half of an instance type onto a real device request, using the container GPU primitive added in #3789. On AWS the instance type *is* the hardware, so nothing is configurable. Floci has one host with fixed cards, so serving a GPU instance type means substituting a local device, and which devices may be lent out is a local decision. The two halves are split accordingly: - How many accelerators an ml.* type carries is a property of AWS, so it ships as data in sagemaker/instance-type-catalog.yaml, mirroring how Ec2InstanceTypeCatalog already carries vcpu and memory for EC2 types. It is kept separate from that catalog because ml.* is its own namespace and must never appear in DescribeInstanceTypes. - Which of this machine's devices may be used is configuration, under floci.services.sagemaker.gpu: enabled, mode and devices. Nothing changes unless enabled is set. It defaults to false, so existing deployments keep launching CPU-only containers, including for GPU instance types. mode exists because daemons disagree on the wire form. It defaults to cdi: Podman resolves only CDI and accepts a count request while attaching no device (containers/podman#22645), so preferring CDI turns a misconfiguration into a refused start rather than a job that quietly trains on CPU. That principle drives the failure cases too: an unlisted GPU-family type, too few allowed devices, an explicit mode with no devices, and InstanceCount above one all fail with a FailureReason instead of falling back to CPU. A job that reports Completed after training on the wrong hardware leaves an artifact that looks legitimate, which is worse than an error. Only the accelerator is substituted. An instance type also implies vCPU and memory, which this does not emulate, consistent with the rest of the codebase: EC2 instance types are metadata for DescribeInstanceTypes and never size a container, RDS records DBInstanceClass without acting on it, and Lambda, ECS and Batch apply limits only where an API supplies an explicit number. Endpoint hosting is unchanged and still CPU-only; the resolver is a separate bean so it can be reused there in a follow-up. * test(sagemaker): cover the GPU refusal paths and the hardware path The GPU feature shipped with unit coverage on the resolver only, so nothing exercised it through CreateTrainingJob. These add both halves. SageMakerGpuIntegrationTest runs everywhere. Every path that refuses a request raises inside SageMakerGpuResolver, before the runner asks the daemon for anything, and the removeIfExists above it already swallows a missing daemon, so an unlisted GPU family, InstanceCount above one, and cdi mode with no configured devices all reach their verdict on a plain runner. A fourth case pins the contract that enabling the feature leaves CPU instance types alone. SageMakerGpuDockerIntegrationTest is opt-in behind -Dgpu.integration.enabled, matching ContainerGpuDockerIntegrationTest, because it needs hardware no CI runner has. Verified against an RTX 5060 Ti through Podman 5.8.2: the container saw exactly the device named in gpu.devices and not the host's other card. The assertion is the container's exit code. nvidia-smi output is redirected rather than piped: a pipeline exits with the status of its last command, so 'nvidia-smi -L | tee' reports success even when nvidia-smi cannot reach the driver, which would be this test passing on a CPU container. * fix(sagemaker): package the instance type catalog in the native image SageMakerInstanceTypeCatalog reads sagemaker/instance-type-catalog.yaml through a constant, which Quarkus's static resource analysis cannot follow, and no glob under quarkus.native.resources.includes matched it. The file was therefore left out of the native image, so enabling floci.services.sagemaker.gpu.enabled there would have failed every training job at catalog load with 'Missing catalog resource sagemaker/instance-type-catalog.yaml'. Ec2InstanceTypeCatalog reads its own catalog the same way and ec2/*.yaml was already listed for exactly this reason. Nothing caught it: JVM tests resolve the file from src/main/resources, and the hardware verification ran a JVM-mode image, so the gap existed only in the artifact neither exercised. NativeImageResourceIncludesTest closes that gap the way NativeImageRuntimeInitializationTest closes the Random-in-the-image-heap one, by moving a native-only failure into ordinary CI. It pairs each resource-path constant passed to getResourceAsStream with the includes globs and fails when none matches, skipping the IAM catalog that application.yml already documents as build-time only. * refactor(sagemaker): match EC2's case handling for instance types isAcceleratorFamily folded case while gpuCount did not, so ML.G5.XLARGE was answered as a GPU family and then reported as missing from the catalog, pointing the caller at the wrong fix. Ec2InstanceTypeCatalog is the precedent and normalizes in neither position: find() looks the type up exactly and familyOf() splits on the first dot without folding. AWS instance types are exact tokens. The repo folds case where AWS defines a value as case-insensitive, such as ACM domain names, regions and content types, which an instance type is not. Dropping the fold rather than adding one to gpuCount keeps both halves agreeing and keeps the pair behaving like EC2's. Also drops the @DisplayName from SageMakerGpuResolverTest. The suite does not use them anywhere else; the method name carries the intent. * docs(sagemaker): clarify GPU training device reuse
This commit is contained in:
1 parent
5a8ffd0272
commit
e14221fe62
13 files changed
+1142
-8
No files matched your search
@@ -1138,6 +1138,57 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
GpuConfig gpu();
|
||||
|
||||
/**
|
||||
* Whether, and how, this host lends its accelerators to training containers.
|
||||
*
|
||||
* <p>How many GPUs an instance type has is an AWS fact and lives in the shipped
|
||||
* catalog; this covers only the local decision of which devices Floci may use.
|
||||
*/
|
||||
interface GpuConfig {
|
||||
/**
|
||||
* Off by default, so an existing deployment keeps launching CPU-only
|
||||
* containers exactly as before.
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean enabled();
|
||||
|
||||
/**
|
||||
* How the device request is expressed on the wire, because daemons disagree.
|
||||
*
|
||||
* <p>Defaults to {@code cdi}: Podman resolves only that form, and accepts the
|
||||
* {@code count} form while attaching no device
|
||||
* (containers/podman#22645). Preferring CDI means a misconfiguration fails
|
||||
* the container start instead of silently training on CPU. Use {@code count}
|
||||
* or {@code device-ids} against Docker.
|
||||
*/
|
||||
@WithDefault("cdi")
|
||||
GpuRequestMode mode();
|
||||
|
||||
/**
|
||||
* The devices Floci may hand out: CDI names such as
|
||||
* {@code nvidia.com/gpu=GPU-<uuid>} for {@code cdi} mode, or daemon device ids
|
||||
* for {@code device-ids} mode.
|
||||
*
|
||||
* <p>Unset allows no device, so a training job in those modes fails rather than
|
||||
* starting. Defaulting to "every device the daemon exposes" would be the wrong
|
||||
* behaviour on a machine sharing GPUs with other workloads.
|
||||
*
|
||||
* <p>Ignored in {@code count} mode, where the daemon does the choosing.
|
||||
*
|
||||
* <p>Optional rather than a defaulted list because SmallRye rejects an empty
|
||||
* string as a collection default: unset simply means no device is allowed.
|
||||
*/
|
||||
Optional<List<String>> devices();
|
||||
}
|
||||
|
||||
enum GpuRequestMode {
|
||||
CDI,
|
||||
DEVICE_IDS,
|
||||
COUNT
|
||||
}
|
||||
}
|
||||
|
||||
interface CodeDeployServiceConfig {
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package io.github.hectorvent.floci.services.sagemaker;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig.SageMakerServiceConfig.GpuRequestMode;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Turns a SageMaker {@code InstanceType} into a device request on a container, or into a
|
||||
* clear refusal.
|
||||
*
|
||||
* <p>Currently used by training jobs. It is kept separate from the training runner so the
|
||||
* same rules can be reused if GPU-backed endpoint hosting is added later.
|
||||
*
|
||||
* <p>The design rule throughout: never answer a GPU request with a CPU container. A job
|
||||
* that asks for {@code ml.g5.xlarge}, trains on CPU and reports {@code Completed} leaves
|
||||
* behind an artifact that looks legitimate, which is worse than a failure. Every path that
|
||||
* cannot honour the request raises {@link UnsupportedResourceException} instead.
|
||||
*
|
||||
* <p>Only the accelerator is mapped. An instance type also implies vCPU and memory, and
|
||||
* Floci does not emulate those: the EC2 catalog is metadata for DescribeInstanceTypes and
|
||||
* never sizes a container, and RDS keeps DBInstanceClass without acting on it. Limits are
|
||||
* applied only where an AWS API hands over an explicit number, as Lambda's MemorySize and
|
||||
* ECS task memory do.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SageMakerGpuResolver {
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final SageMakerInstanceTypeCatalog catalog;
|
||||
|
||||
@Inject
|
||||
public SageMakerGpuResolver(EmulatorConfig config, SageMakerInstanceTypeCatalog catalog) {
|
||||
this.config = config;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised when the request names hardware this host cannot stand in for. Callers surface
|
||||
* the message as the AWS failure reason, so it has to say what is wrong and what would
|
||||
* fix it.
|
||||
*/
|
||||
public static class UnsupportedResourceException extends RuntimeException {
|
||||
public UnsupportedResourceException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a device request to {@code builder} when the instance type calls for one.
|
||||
*
|
||||
* @param instanceType the requested {@code ml.*} type, as given in the AWS request
|
||||
* @param instanceCount instances requested; anything above one is refused, since a
|
||||
* single container is not distributed training
|
||||
* @throws UnsupportedResourceException when the request cannot be honoured
|
||||
*/
|
||||
public void applyTo(ContainerBuilder.Builder builder, String instanceType, int instanceCount) {
|
||||
EmulatorConfig.SageMakerServiceConfig.GpuConfig gpu = config.services().sagemaker().gpu();
|
||||
if (!gpu.enabled()) {
|
||||
// Feature off: behave exactly as before, including for GPU instance types.
|
||||
// Turning it on is what opts a deployment into the stricter rules below.
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<Integer> catalogued = catalog.gpuCount(instanceType);
|
||||
if (catalogued.isEmpty()) {
|
||||
if (SageMakerInstanceTypeCatalog.isAcceleratorFamily(instanceType)) {
|
||||
throw new UnsupportedResourceException(
|
||||
"Instance type " + instanceType + " is a GPU family but is not in Floci's "
|
||||
+ "SageMaker instance type catalog, so the number of accelerators it "
|
||||
+ "should receive is unknown. Add it to the catalog or choose a "
|
||||
+ "listed type.");
|
||||
}
|
||||
// An unlisted non-accelerator type is a CPU job, which needs nothing from us.
|
||||
return;
|
||||
}
|
||||
|
||||
int requested = catalogued.get();
|
||||
if (requested == 0) {
|
||||
return;
|
||||
}
|
||||
if (instanceCount > 1) {
|
||||
throw new UnsupportedResourceException(
|
||||
"Floci runs a training job as a single container, so InstanceCount " + instanceCount
|
||||
+ " with GPU instance type " + instanceType + " cannot be honoured. Use "
|
||||
+ "InstanceCount 1.");
|
||||
}
|
||||
|
||||
List<String> devices = gpu.devices().orElse(List.of());
|
||||
GpuRequestMode mode = gpu.mode();
|
||||
if (mode != GpuRequestMode.COUNT && !devices.isEmpty() && devices.size() < requested) {
|
||||
throw new UnsupportedResourceException(
|
||||
"Instance type " + instanceType + " needs " + requested + " GPUs but only "
|
||||
+ devices.size() + " device(s) are allowed by "
|
||||
+ "floci.services.sagemaker.gpu.devices.");
|
||||
}
|
||||
|
||||
switch (mode) {
|
||||
case CDI -> {
|
||||
requireDevicesConfigured(devices, "cdi", instanceType);
|
||||
builder.withCdiDevices(devices.subList(0, requested));
|
||||
}
|
||||
case DEVICE_IDS -> {
|
||||
requireDevicesConfigured(devices, "device-ids", instanceType);
|
||||
builder.withGpuDeviceIds(devices.subList(0, requested));
|
||||
}
|
||||
// The daemon picks the devices, so no allowlist applies.
|
||||
case COUNT -> builder.withGpuCount(requested);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Both explicit-device modes need to be told which devices exist. Defaulting to "all
|
||||
* of them" would quietly hand Floci every GPU on a machine that is usually sharing
|
||||
* them with something else.
|
||||
*/
|
||||
private static void requireDevicesConfigured(List<String> devices, String mode, String instanceType) {
|
||||
if (devices.isEmpty()) {
|
||||
throw new UnsupportedResourceException(
|
||||
"GPU support is enabled in " + mode + " mode but "
|
||||
+ "floci.services.sagemaker.gpu.devices is empty, so there is no device to "
|
||||
+ "give " + instanceType + ". List the devices Floci may use, or switch to "
|
||||
+ "count mode to let the daemon choose.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package io.github.hectorvent.floci.services.sagemaker;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* How many accelerators each SageMaker {@code ml.*} instance type carries.
|
||||
*
|
||||
* <p>This is shipped data rather than configuration for the same reason
|
||||
* {@code Ec2InstanceTypeCatalog} is: the GPU count of an {@code ml.g5.xlarge} is a fact
|
||||
* about AWS, identical for everyone, and not something an operator should have to
|
||||
* restate. What the local machine is willing to hand over is the separate, genuinely
|
||||
* local decision, and lives under {@code floci.services.sagemaker.gpu}.
|
||||
*
|
||||
* <p>Deliberately not merged into the EC2 catalog: {@code ml.*} is its own namespace and
|
||||
* these types must never appear in {@code DescribeInstanceTypes}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SageMakerInstanceTypeCatalog {
|
||||
|
||||
private static final String CATALOG_RESOURCE_NAME = "sagemaker/instance-type-catalog.yaml";
|
||||
private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory());
|
||||
|
||||
/**
|
||||
* Families whose members carry accelerators. Used only to decide whether an unknown
|
||||
* type should be refused rather than run on CPU: a caller naming an unlisted
|
||||
* {@code ml.g*} clearly wanted a GPU, and silently giving them CPU would produce a
|
||||
* job that reports Completed with a legitimate-looking artifact.
|
||||
*
|
||||
* <p>Never used to infer a count. Counts vary within a family, which is why the
|
||||
* catalog is a table.
|
||||
*/
|
||||
private static final Set<String> ACCELERATOR_FAMILY_PREFIXES =
|
||||
Set.of("ml.g", "ml.p", "ml.inf", "ml.trn");
|
||||
|
||||
private volatile Loaded loaded;
|
||||
|
||||
public SageMakerInstanceTypeCatalog() {
|
||||
// Load lazily, matching Ec2InstanceTypeCatalog: a deployment that never touches
|
||||
// SageMaker should not pay for resource loading at bean construction.
|
||||
}
|
||||
|
||||
SageMakerInstanceTypeCatalog(Catalog catalog) {
|
||||
this.loaded = new Loaded(catalog);
|
||||
}
|
||||
|
||||
/**
|
||||
* The accelerator count for a type, or empty when the catalog does not describe it.
|
||||
* An empty result is not "no GPU": see {@link #isAcceleratorFamily(String)}.
|
||||
*/
|
||||
public Optional<Integer> gpuCount(String instanceType) {
|
||||
if (instanceType == null || instanceType.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
CatalogInstanceType found = loaded().byName.get(instanceType.trim());
|
||||
return found == null ? Optional.empty() : Optional.of(found.gpuCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the type belongs to a family that carries accelerators on AWS, regardless of
|
||||
* whether this catalog lists the specific size.
|
||||
*
|
||||
* <p>Case sensitive, like {@link #gpuCount(String)} and like EC2's {@code find} and
|
||||
* {@code familyOf}: AWS instance types are exact tokens, so folding case here would make
|
||||
* this disagree with the catalog lookup and answer "GPU family" for a spelling the lookup
|
||||
* then reports as missing from the catalog.
|
||||
*/
|
||||
public static boolean isAcceleratorFamily(String instanceType) {
|
||||
if (instanceType == null || instanceType.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String normalized = instanceType.trim();
|
||||
return ACCELERATOR_FAMILY_PREFIXES.stream().anyMatch(normalized::startsWith);
|
||||
}
|
||||
|
||||
private Loaded loaded() {
|
||||
Loaded current = loaded;
|
||||
if (current == null) {
|
||||
synchronized (this) {
|
||||
current = loaded;
|
||||
if (current == null) {
|
||||
current = new Loaded(readCatalog());
|
||||
loaded = current;
|
||||
}
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
private static Catalog readCatalog() {
|
||||
try (InputStream in = Thread.currentThread().getContextClassLoader()
|
||||
.getResourceAsStream(CATALOG_RESOURCE_NAME)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("Missing catalog resource " + CATALOG_RESOURCE_NAME);
|
||||
}
|
||||
return YAML_MAPPER.readValue(in, Catalog.class);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Could not read " + CATALOG_RESOURCE_NAME, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Loaded {
|
||||
private final Map<String, CatalogInstanceType> byName;
|
||||
|
||||
private Loaded(Catalog catalog) {
|
||||
Map<String, CatalogInstanceType> index = new LinkedHashMap<>();
|
||||
for (CatalogInstanceType type : catalog.instanceTypes) {
|
||||
index.put(type.instanceType, type);
|
||||
}
|
||||
this.byName = Map.copyOf(index);
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static final class Catalog {
|
||||
public List<CatalogInstanceType> instanceTypes = List.of();
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static final class CatalogInstanceType {
|
||||
public String instanceType;
|
||||
public int gpuCount;
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -54,6 +54,7 @@ public class SageMakerTrainingRunner implements ContainerTeardown, Resettable {
|
||||
private final ContainerDetector containerDetector;
|
||||
private final S3Service s3Service;
|
||||
private final ObjectMapper mapper;
|
||||
private final SageMakerGpuResolver gpuResolver;
|
||||
// Replaced by afterReset() after a state reset, whose container teardown shuts this pool down.
|
||||
private volatile ExecutorService executor = Executors.newCachedThreadPool();
|
||||
private final ConcurrentHashMap<String, String> containers = new ConcurrentHashMap<>();
|
||||
@@ -66,7 +67,8 @@ public class SageMakerTrainingRunner implements ContainerTeardown, Resettable {
|
||||
@Inject
|
||||
public SageMakerTrainingRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
ContainerLogStreamer logStreamer, EmulatorConfig config,
|
||||
ContainerDetector containerDetector, S3Service s3Service, ObjectMapper mapper) {
|
||||
ContainerDetector containerDetector, S3Service s3Service, ObjectMapper mapper,
|
||||
SageMakerGpuResolver gpuResolver) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
@@ -74,6 +76,7 @@ public class SageMakerTrainingRunner implements ContainerTeardown, Resettable {
|
||||
this.containerDetector = containerDetector;
|
||||
this.s3Service = s3Service;
|
||||
this.mapper = mapper;
|
||||
this.gpuResolver = gpuResolver;
|
||||
}
|
||||
|
||||
public void runAsync(TrainingJobResource job, SageMakerService service) {
|
||||
@@ -95,6 +98,10 @@ public class SageMakerTrainingRunner implements ContainerTeardown, Resettable {
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation();
|
||||
SageMakerEndpointManager.applyEntrypoint(builder, job.algorithmSpecification, "train");
|
||||
// Throws when the requested instance type asks for hardware this host cannot
|
||||
// stand in for, so the job fails with a reason rather than quietly training
|
||||
// on CPU and producing an artifact that looks legitimate.
|
||||
gpuResolver.applyTo(builder, instanceType(job), instanceCount(job));
|
||||
ContainerSpec spec = builder.build();
|
||||
containerId = lifecycleManager.create(spec);
|
||||
containers.put(job.trainingJobName, containerId);
|
||||
@@ -324,6 +331,16 @@ public class SageMakerTrainingRunner implements ContainerTeardown, Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
private static String instanceType(TrainingJobResource job) {
|
||||
return SageMakerEndpointManager.string(job.resourceConfig.get("InstanceType"));
|
||||
}
|
||||
|
||||
/** Absent or unparseable means one, matching how a single-instance job is described. */
|
||||
private static int instanceCount(TrainingJobResource job) {
|
||||
Object value = job.resourceConfig.get("InstanceCount");
|
||||
return value instanceof Number n ? n.intValue() : 1;
|
||||
}
|
||||
|
||||
private Duration timeout(TrainingJobResource job) {
|
||||
Object value = job.stoppingCondition.get("MaxRuntimeInSeconds");
|
||||
if (value instanceof Number n) {
|
||||
|
||||
Reference in new issue
Block a user