mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
@@ -0,0 +1,143 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.PathMatcher;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Guards the GraalVM native-image build against a classpath resource that is read at runtime but
|
||||
* never packaged.
|
||||
*
|
||||
* <p>Quarkus's static analysis finds an inline literal such as
|
||||
* {@code getResourceAsStream("/redshift/bootstrap-catalog.sql")}, so those need no registration.
|
||||
* It cannot follow a constant, so {@code getResourceAsStream(CATALOG_RESOURCE_NAME)} leaves the
|
||||
* file out of the image and the first read fails at runtime with a missing-resource error. The
|
||||
* remedy is a matching glob under {@code quarkus.native.resources.includes} in
|
||||
* {@code application.yml}.
|
||||
*
|
||||
* <p>Like {@link NativeImageRuntimeInitializationTest}, this failure only surfaces in the slow
|
||||
* native build and never in the JVM CI jobs, so it moves the check into ordinary CI. Regression
|
||||
* context: the SageMaker instance type catalog shipped reading
|
||||
* {@code sagemaker/instance-type-catalog.yaml} through a constant without the matching include,
|
||||
* which would have failed every GPU training job in the native image while passing every JVM test.
|
||||
*/
|
||||
class NativeImageResourceIncludesTest {
|
||||
|
||||
private static final Path MAIN_SOURCE_ROOT = Path.of("src", "main", "java");
|
||||
private static final Path APPLICATION_YML = Path.of("src", "main", "resources", "application.yml");
|
||||
private static final Path MAIN_RESOURCE_ROOT = Path.of("src", "main", "resources");
|
||||
|
||||
private static final String JAVA_SUFFIX = ".java";
|
||||
|
||||
/** A {@code static final String NAME = "some/path.ext";} declaration holding a resource path. */
|
||||
private static final Pattern RESOURCE_CONSTANT = Pattern.compile(
|
||||
"static\\s+final\\s+String\\s+(\\w+)\\s*=\\s*\"(/?[\\w.\\-]+(?:/[\\w.\\-]+)+\\.[A-Za-z0-9]+)\"");
|
||||
|
||||
/**
|
||||
* Read while the image is built, not at runtime. {@code AwsManagedPolicies} parses the catalog
|
||||
* during the build and keeps the parsed form in the image heap, so including the 3.5 MB of
|
||||
* source files would only be a second copy. {@code application.yml} says the same.
|
||||
*/
|
||||
private static final Set<String> BUILD_TIME_ONLY = Set.of(
|
||||
"iam/managed-policies.yaml",
|
||||
"iam/managed-policy-documents.json",
|
||||
"iam/managed-policy-versions.json");
|
||||
|
||||
@Test
|
||||
void everyResourceReadThroughAConstantIsIncludedInTheNativeImage() throws IOException {
|
||||
List<PathMatcher> includes = parseIncludes();
|
||||
Map<String, String> offenders = new LinkedHashMap<>();
|
||||
|
||||
try (Stream<Path> sources = Files.walk(MAIN_SOURCE_ROOT)) {
|
||||
sources.filter(p -> p.toString().endsWith(JAVA_SUFFIX)).forEach(source -> {
|
||||
for (String resource : resourcesReadThroughAConstant(source)) {
|
||||
if (BUILD_TIME_ONLY.contains(resource)) {
|
||||
continue;
|
||||
}
|
||||
// Only a file this repository actually ships can be registered. A constant
|
||||
// naming something from a dependency is that dependency's problem.
|
||||
if (!Files.exists(MAIN_RESOURCE_ROOT.resolve(resource))) {
|
||||
continue;
|
||||
}
|
||||
if (includes.stream().noneMatch(m -> m.matches(Path.of(resource)))) {
|
||||
offenders.put(resource, source.toString());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
assertTrue(offenders.isEmpty(),
|
||||
"These resources are read at runtime through a constant, which Quarkus's static analysis "
|
||||
+ "cannot follow, but no glob in " + APPLICATION_YML + " under "
|
||||
+ "quarkus.native.resources.includes matches them. The native image will not contain "
|
||||
+ "them and the first read will fail at runtime. Add an include for each:\n "
|
||||
+ offenders.entrySet().stream()
|
||||
.map(e -> e.getKey() + " (read by " + e.getValue() + ")")
|
||||
.reduce((a, b) -> a + "\n " + b).orElse(""));
|
||||
}
|
||||
|
||||
/** Resource paths declared as a constant in {@code javaFile} and passed to getResourceAsStream there. */
|
||||
private List<String> resourcesReadThroughAConstant(Path javaFile) {
|
||||
String source;
|
||||
try {
|
||||
source = Files.readString(javaFile);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Unable to read source file " + javaFile, e);
|
||||
}
|
||||
List<String> found = new ArrayList<>();
|
||||
if (!source.contains("getResourceAsStream")) {
|
||||
return found;
|
||||
}
|
||||
Matcher constants = RESOURCE_CONSTANT.matcher(source);
|
||||
while (constants.find()) {
|
||||
String name = constants.group(1);
|
||||
String value = constants.group(2);
|
||||
if (source.contains("getResourceAsStream(" + name + ")")
|
||||
|| source.contains("getResourceAsStream(\n")
|
||||
&& source.contains(name + ")")) {
|
||||
found.add(value.startsWith("/") ? value.substring(1) : value);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The {@code quarkus.native.resources.includes} globs, as matchers over classpath-relative paths. */
|
||||
private List<PathMatcher> parseIncludes() throws IOException {
|
||||
List<String> lines = Files.readAllLines(APPLICATION_YML);
|
||||
List<PathMatcher> matchers = new ArrayList<>();
|
||||
boolean inIncludes = false;
|
||||
for (String raw : lines) {
|
||||
String line = raw.strip();
|
||||
if (line.startsWith("includes:")) {
|
||||
inIncludes = true;
|
||||
continue;
|
||||
}
|
||||
if (inIncludes) {
|
||||
if (!line.startsWith("- ")) {
|
||||
if (!line.isEmpty() && !line.startsWith("#")) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
matchers.add(FileSystems.getDefault().getPathMatcher("glob:" + line.substring(2).strip()));
|
||||
}
|
||||
}
|
||||
assertTrue(!matchers.isEmpty(), "Found no quarkus.native.resources.includes entries in " + APPLICATION_YML);
|
||||
return matchers;
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package io.github.hectorvent.floci.services.sagemaker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Proves an {@code ml.*} GPU instance type reaches a real accelerator, end to end through
|
||||
* {@code CreateTrainingJob} rather than through the container layer directly.
|
||||
*
|
||||
* <p>Opt-in for the same reason as {@link
|
||||
* io.github.hectorvent.floci.core.common.docker.ContainerGpuDockerIntegrationTest}: it needs
|
||||
* hardware no CI runner has. Run it with {@code -Dgpu.integration.enabled=true} on a host with a
|
||||
* GPU, naming the device the same way the feature's own configuration does:
|
||||
*
|
||||
* <pre>
|
||||
* ./mvnw test -Dtest=SageMakerGpuDockerIntegrationTest \
|
||||
* -Dgpu.integration.enabled=true \
|
||||
* -Dgpu.integration.cdi-device=nvidia.com/gpu=GPU-<uuid>
|
||||
* </pre>
|
||||
*
|
||||
* <p>Without the flag it skips, leaving {@link SageMakerGpuResolverTest} and {@link
|
||||
* SageMakerGpuIntegrationTest} as the coverage that runs by default. Those pin every path that
|
||||
* refuses a request; this pins the one that honours it.
|
||||
*
|
||||
* <p>The assertion is the container's exit code, not a log line. The image runs {@code nvidia-smi},
|
||||
* which the runtime injects alongside the device, so it is absent when no device was attached: a
|
||||
* job that quietly fell back to CPU exits nonzero and reports Failed. Naming a device also makes
|
||||
* the check exact, since the daemon must hand over that card rather than any card.
|
||||
*
|
||||
* <p>With no device named the test asks for every GPU using the count form, which is the shape to
|
||||
* run against Docker. Podman accepts that form and attaches nothing
|
||||
* (containers/podman#22645), so that combination fails here by design, which is the same reason
|
||||
* {@code mode} defaults to {@code cdi}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SageMakerGpuDockerIntegrationTest.GpuHardwareProfile.class)
|
||||
class SageMakerGpuDockerIntegrationTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SageMakerGpuDockerIntegrationTest.class);
|
||||
|
||||
private static final String ENABLED_PROPERTY = "gpu.integration.enabled";
|
||||
private static final String CDI_DEVICE_PROPERTY = "gpu.integration.cdi-device";
|
||||
private static final String IMAGE_PROPERTY = "gpu.integration.image";
|
||||
private static final String DEFAULT_IMAGE = "docker.io/nvidia/cuda:12.8.1-base-ubuntu24.04";
|
||||
|
||||
/**
|
||||
* Mirrors the deployment-side configuration the feature documents. A named device selects
|
||||
* {@code cdi} mode and the allowlist; with none, {@code count} lets the daemon choose.
|
||||
*/
|
||||
public static class GpuHardwareProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
Map<String, String> overrides = new HashMap<>();
|
||||
overrides.put("floci.services.sagemaker.gpu.enabled", "true");
|
||||
String device = System.getProperty(CDI_DEVICE_PROPERTY);
|
||||
if (device != null && !device.isBlank()) {
|
||||
overrides.put("floci.services.sagemaker.gpu.mode", "cdi");
|
||||
overrides.put("floci.services.sagemaker.gpu.devices", device);
|
||||
} else {
|
||||
overrides.put("floci.services.sagemaker.gpu.mode", "count");
|
||||
}
|
||||
return overrides;
|
||||
}
|
||||
}
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/sagemaker/aws4_request";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void requireGpuEnabledDaemon() {
|
||||
Assumptions.assumeTrue(Boolean.getBoolean(ENABLED_PROPERTY),
|
||||
"GPU hardware tests are opt-in: run with -D" + ENABLED_PROPERTY + "=true on a host with a GPU");
|
||||
Assumptions.assumeTrue(isDockerAvailable(),
|
||||
"A container daemon must be available for GPU integration tests");
|
||||
}
|
||||
|
||||
@Test
|
||||
void gpuInstanceTypeTrainsOnTheRequestedDevice() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "sm-gpu-" + suffix;
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
String job = "sm-gpu-" + suffix;
|
||||
String image = System.getProperty(IMAGE_PROPERTY, DEFAULT_IMAGE);
|
||||
|
||||
// nvidia-smi is injected with the device, so its absence is the clearest signal that
|
||||
// nothing was attached. Writing the UUID into /opt/ml/model makes Floci upload the
|
||||
// evidence rather than leaving it in a log.
|
||||
//
|
||||
// Redirect rather than pipe: a pipeline exits with the status of its last command, so
|
||||
// `nvidia-smi -L | tee` reports success even when nvidia-smi could not reach the driver.
|
||||
// That would be this test passing on a CPU container, which is the exact failure it exists
|
||||
// to catch.
|
||||
post("SageMaker.CreateTrainingJob", """
|
||||
{
|
||||
"TrainingJobName":"%s",
|
||||
"AlgorithmSpecification":{
|
||||
"TrainingImage":"%s",
|
||||
"ContainerEntrypoint":["/bin/sh","-c"],
|
||||
"ContainerArguments":["mkdir -p /opt/ml/model && nvidia-smi -L > /opt/ml/model/devices.txt && cat /opt/ml/model/devices.txt"]
|
||||
},
|
||||
"OutputDataConfig":{"S3OutputPath":"s3://%s/output"},
|
||||
"ResourceConfig":{"InstanceType":"ml.g5.xlarge","InstanceCount":1,"VolumeSizeInGB":1},
|
||||
"StoppingCondition":{"MaxRuntimeInSeconds":300}
|
||||
}
|
||||
""".formatted(job, image, bucket)).then().statusCode(200);
|
||||
|
||||
Response describe = awaitTerminal(job);
|
||||
String status = describe.path("TrainingJobStatus");
|
||||
String reason = describe.path("FailureReason");
|
||||
assertEquals("Completed", status,
|
||||
"ml.g5.xlarge did not reach a GPU: " + (reason == null ? "no FailureReason" : reason));
|
||||
|
||||
String artifact = describe.path("ModelArtifacts.S3ModelArtifacts");
|
||||
assertTrue(artifact != null && artifact.endsWith("model.tar.gz"),
|
||||
"no model artifact was uploaded: " + artifact);
|
||||
LOG.infov("GPU training job completed, artifact at {0}", artifact);
|
||||
}
|
||||
|
||||
private Response awaitTerminal(String job) throws Exception {
|
||||
long deadline = System.currentTimeMillis() + Duration.ofSeconds(300).toMillis();
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Response describe = post("SageMaker.DescribeTrainingJob",
|
||||
"{\"TrainingJobName\":\"%s\"}".formatted(job));
|
||||
describe.then().statusCode(200);
|
||||
String status = describe.path("TrainingJobStatus");
|
||||
if ("Failed".equals(status) || "Completed".equals(status) || "Stopped".equals(status)) {
|
||||
return describe;
|
||||
}
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
throw new AssertionError("Timed out waiting for training job " + job);
|
||||
}
|
||||
|
||||
private Response post(String target, String body) {
|
||||
return given().header("Authorization", AUTH)
|
||||
.header("X-Amz-Target", target)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warn("No container daemon available for the SageMaker GPU integration test", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package io.github.hectorvent.floci.services.sagemaker;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Covers the GPU refusal paths, which need no GPU and no container daemon.
|
||||
*
|
||||
* <p>{@link SageMakerGpuResolver} raises before the runner asks the daemon for anything, and
|
||||
* {@code removeIfExists} on the line above it swallows a missing daemon, so every case here
|
||||
* reaches its verdict on a plain CI runner. The hardware path is the opposite and lives in
|
||||
* {@link SageMakerGpuDockerIntegrationTest}, which skips without a GPU.
|
||||
*
|
||||
* <p>What is being pinned is the contract that a request Floci cannot honour fails with a
|
||||
* reason naming the fix, rather than falling back to CPU. A job that reports {@code Completed}
|
||||
* after training on the wrong hardware leaves an artifact that looks legitimate.
|
||||
*
|
||||
* <p>The profile turns the feature on because {@code application.yml} ships it off. Devices are
|
||||
* deliberately left unset, which is what makes the third case reachable.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SageMakerGpuIntegrationTest.GpuEnabledProfile.class)
|
||||
class SageMakerGpuIntegrationTest {
|
||||
|
||||
public static class GpuEnabledProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.sagemaker.gpu.enabled", "true");
|
||||
}
|
||||
}
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/sagemaker/aws4_request";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void gpuFamilyMissingFromTheCatalogFailsNamingTheCatalog() throws Exception {
|
||||
String job = submit("ml.p5.48xlarge", 1);
|
||||
String reason = awaitFailureReason(job);
|
||||
|
||||
assertTrue(reason.contains("ml.p5.48xlarge"), reason);
|
||||
assertTrue(reason.contains("catalog"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceCountAboveOneFailsRatherThanTrainingOnOneContainer() throws Exception {
|
||||
String job = submit("ml.g5.xlarge", 2);
|
||||
String reason = awaitFailureReason(job);
|
||||
|
||||
assertTrue(reason.contains("InstanceCount 2"), reason);
|
||||
assertTrue(reason.contains("ml.g5.xlarge"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cdiModeWithNoConfiguredDevicesFailsRatherThanTakingEveryGpu() throws Exception {
|
||||
String job = submit("ml.g5.xlarge", 1);
|
||||
String reason = awaitFailureReason(job);
|
||||
|
||||
assertTrue(reason.contains("floci.services.sagemaker.gpu.devices"), reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enabling the feature must not change what a CPU instance type does. The job's outcome
|
||||
* depends on whether a daemon is present, so only the reason is asserted: whatever happens,
|
||||
* it must not be the resolver refusing the request.
|
||||
*/
|
||||
@Test
|
||||
void cpuInstanceTypeIsNotRefusedWhenGpuSupportIsEnabled() throws Exception {
|
||||
String job = submit("ml.m5.large", 1);
|
||||
Response describe = awaitTerminal(job);
|
||||
String reason = describe.path("FailureReason") == null ? "" : describe.path("FailureReason");
|
||||
|
||||
assertFalse(reason.contains("floci.services.sagemaker.gpu"), reason);
|
||||
assertFalse(reason.contains("catalog"), reason);
|
||||
}
|
||||
|
||||
private String submit(String instanceType, int instanceCount) {
|
||||
String job = "sm-gpu-" + Long.toString(System.nanoTime(), 36);
|
||||
post("SageMaker.CreateTrainingJob", """
|
||||
{
|
||||
"TrainingJobName":"%s",
|
||||
"AlgorithmSpecification":{"TrainingImage":"busybox:stable","TrainingInputMode":"File"},
|
||||
"OutputDataConfig":{"S3OutputPath":"s3://sm-gpu-out/output"},
|
||||
"ResourceConfig":{"InstanceType":"%s","InstanceCount":%d,"VolumeSizeInGB":1},
|
||||
"StoppingCondition":{"MaxRuntimeInSeconds":60}
|
||||
}
|
||||
""".formatted(job, instanceType, instanceCount))
|
||||
.then().statusCode(200);
|
||||
return job;
|
||||
}
|
||||
|
||||
private String awaitFailureReason(String job) throws Exception {
|
||||
Response describe = awaitTerminal(job);
|
||||
assertEquals("Failed", describe.path("TrainingJobStatus"),
|
||||
"expected the request to be refused, not honoured");
|
||||
String reason = describe.path("FailureReason");
|
||||
assertTrue(reason != null && !reason.isBlank(), "Failed with no FailureReason");
|
||||
return reason;
|
||||
}
|
||||
|
||||
private Response awaitTerminal(String job) throws Exception {
|
||||
long deadline = System.currentTimeMillis() + Duration.ofSeconds(60).toMillis();
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Response describe = post("SageMaker.DescribeTrainingJob",
|
||||
"{\"TrainingJobName\":\"%s\"}".formatted(job));
|
||||
describe.then().statusCode(200);
|
||||
String status = describe.path("TrainingJobStatus");
|
||||
if ("Failed".equals(status) || "Completed".equals(status) || "Stopped".equals(status)) {
|
||||
return describe;
|
||||
}
|
||||
Thread.sleep(200);
|
||||
}
|
||||
throw new AssertionError("Timed out waiting for training job " + job + " to reach a terminal state");
|
||||
}
|
||||
|
||||
private Response post(String target, String body) {
|
||||
return given().header("Authorization", AUTH)
|
||||
.header("X-Amz-Target", target)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
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 io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import com.github.dockerjava.api.model.DeviceRequest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SageMakerGpuResolverTest {
|
||||
|
||||
private static final String UUID_A = "nvidia.com/gpu=GPU-aaaaaaaa";
|
||||
private static final String UUID_B = "nvidia.com/gpu=GPU-bbbbbbbb";
|
||||
private static final String UUID_C = "nvidia.com/gpu=GPU-cccccccc";
|
||||
private static final String UUID_D = "nvidia.com/gpu=GPU-dddddddd";
|
||||
|
||||
@Test
|
||||
void disabledByDefaultLeavesEvenGpuInstanceTypesAlone() {
|
||||
Fixture fixture = new Fixture(false, GpuRequestMode.CDI, List.of(UUID_A));
|
||||
|
||||
ContainerSpec spec = fixture.resolve("ml.g5.xlarge", 1);
|
||||
|
||||
// The guard on every existing deployment: opting out means nothing changes,
|
||||
// including for instance types that would otherwise ask for hardware.
|
||||
assertEquals(List.of(), spec.deviceRequests());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpuInstanceTypeGetsNoDevice() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI, List.of(UUID_A));
|
||||
|
||||
assertEquals(List.of(), fixture.resolve("ml.m5.large", 1).deviceRequests());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownNonAcceleratorTypeIsTreatedAsCpu() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI, List.of(UUID_A));
|
||||
|
||||
// Not in the catalog and not a GPU family: a CPU job Floci simply does not
|
||||
// have metadata for, which is no reason to fail it.
|
||||
assertEquals(List.of(), fixture.resolve("ml.c7i.12xlarge", 1).deviceRequests());
|
||||
}
|
||||
|
||||
@Test
|
||||
void gpuInstanceTypeRequestsItsCataloguedDeviceCount() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI, List.of(UUID_A, UUID_B));
|
||||
|
||||
ContainerSpec spec = fixture.resolve("ml.g5.xlarge", 1);
|
||||
|
||||
DeviceRequest request = spec.deviceRequests().get(0);
|
||||
assertEquals("cdi", request.getDriver());
|
||||
assertEquals(List.of(UUID_A), request.getDeviceIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiGpuTypeTakesAsManyDevicesAsTheCatalogSays() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI,
|
||||
List.of(UUID_A, UUID_B, UUID_C, UUID_D));
|
||||
|
||||
// ml.g5.12xlarge is four devices on AWS, so a host offering four gets all four
|
||||
// in one container. Counts come from the catalog rather than from matching
|
||||
// ml.g*, because they vary within a family.
|
||||
ContainerSpec spec = fixture.resolve("ml.g5.12xlarge", 1);
|
||||
|
||||
assertEquals(List.of(UUID_A, UUID_B, UUID_C, UUID_D),
|
||||
spec.deviceRequests().get(0).getDeviceIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void devicesAreTakenInOrderSoASmallerTypeDoesNotClaimEverything() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI,
|
||||
List.of(UUID_A, UUID_B, UUID_C, UUID_D));
|
||||
|
||||
// A one-GPU type on a four-GPU host takes one device, not the whole allowlist.
|
||||
assertEquals(List.of(UUID_A), fixture.resolve("ml.g5.xlarge", 1)
|
||||
.deviceRequests().get(0).getDeviceIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiGpuTypeIsRefusedWhenTheHostAllowsFewerDevices() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI, List.of(UUID_A, UUID_B));
|
||||
|
||||
SageMakerGpuResolver.UnsupportedResourceException thrown = assertThrows(
|
||||
SageMakerGpuResolver.UnsupportedResourceException.class,
|
||||
() -> fixture.resolve("ml.g5.12xlarge", 1));
|
||||
assertTrue(thrown.getMessage().contains("needs 4 GPUs"), thrown.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceIdsModeUsesTheDaemonIdForm() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.DEVICE_IDS, List.of("0", "1"));
|
||||
|
||||
DeviceRequest request = fixture.resolve("ml.g5.xlarge", 1).deviceRequests().get(0);
|
||||
|
||||
assertEquals(List.of("0"), request.getDeviceIds());
|
||||
assertEquals(List.of(List.of("gpu")), request.getCapabilities());
|
||||
}
|
||||
|
||||
@Test
|
||||
void countModeLetsTheDaemonChooseAndIgnoresTheAllowlist() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.COUNT, List.of());
|
||||
|
||||
DeviceRequest request = fixture.resolve("ml.g5.xlarge", 1).deviceRequests().get(0);
|
||||
|
||||
assertEquals(1, request.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceleratorTypeMissingFromTheCatalogIsRefused() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI, List.of(UUID_A));
|
||||
|
||||
// The case this whole class exists to prevent: the caller asked for a GPU, so
|
||||
// running on CPU and reporting Completed would hand back an artifact that looks
|
||||
// legitimate.
|
||||
SageMakerGpuResolver.UnsupportedResourceException thrown = assertThrows(
|
||||
SageMakerGpuResolver.UnsupportedResourceException.class,
|
||||
() -> fixture.resolve("ml.p5.48xlarge", 1));
|
||||
assertTrue(thrown.getMessage().contains("not in Floci's"), thrown.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleInstancesAreRefusedRatherThanPretended() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI, List.of(UUID_A, UUID_B));
|
||||
|
||||
SageMakerGpuResolver.UnsupportedResourceException thrown = assertThrows(
|
||||
SageMakerGpuResolver.UnsupportedResourceException.class,
|
||||
() -> fixture.resolve("ml.g5.xlarge", 2));
|
||||
assertTrue(thrown.getMessage().contains("InstanceCount 2"), thrown.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitModeWithNoDevicesConfiguredIsRefused() {
|
||||
Fixture fixture = new Fixture(true, GpuRequestMode.CDI, List.of());
|
||||
|
||||
SageMakerGpuResolver.UnsupportedResourceException thrown = assertThrows(
|
||||
SageMakerGpuResolver.UnsupportedResourceException.class,
|
||||
() -> fixture.resolve("ml.g5.xlarge", 1));
|
||||
assertTrue(thrown.getMessage().contains("devices is empty"), thrown.getMessage());
|
||||
}
|
||||
|
||||
/** Wires a real ContainerBuilder so the assertions see the request actually built. */
|
||||
private static final class Fixture {
|
||||
private final SageMakerGpuResolver resolver;
|
||||
private final ContainerBuilder containerBuilder;
|
||||
|
||||
private Fixture(boolean enabled, GpuRequestMode mode, List<String> devices) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.SageMakerServiceConfig sagemaker =
|
||||
mock(EmulatorConfig.SageMakerServiceConfig.class);
|
||||
EmulatorConfig.SageMakerServiceConfig.GpuConfig gpu =
|
||||
mock(EmulatorConfig.SageMakerServiceConfig.GpuConfig.class);
|
||||
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
|
||||
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.sagemaker()).thenReturn(sagemaker);
|
||||
when(sagemaker.gpu()).thenReturn(gpu);
|
||||
when(gpu.enabled()).thenReturn(enabled);
|
||||
when(gpu.mode()).thenReturn(mode);
|
||||
when(gpu.devices()).thenReturn(Optional.of(devices));
|
||||
when(config.docker()).thenReturn(docker);
|
||||
when(docker.imageRegistryBase()).thenReturn(Optional.empty());
|
||||
|
||||
this.containerBuilder = new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class), mock(CurrentContainerNetworkResolver.class));
|
||||
this.resolver = new SageMakerGpuResolver(config, new SageMakerInstanceTypeCatalog());
|
||||
}
|
||||
|
||||
private ContainerSpec resolve(String instanceType, int instanceCount) {
|
||||
ContainerBuilder.Builder builder = containerBuilder.newContainer("alpine");
|
||||
resolver.applyTo(builder, instanceType, instanceCount);
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -74,6 +74,7 @@ class SageMakerTrainingRunnerTest {
|
||||
private static SageMakerTrainingRunner runner() {
|
||||
return new SageMakerTrainingRunner(mock(ContainerBuilder.class), mock(ContainerLifecycleManager.class),
|
||||
mock(ContainerLogStreamer.class), mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
|
||||
mock(ContainerDetector.class), mock(S3Service.class), new ObjectMapper());
|
||||
mock(ContainerDetector.class), mock(S3Service.class), new ObjectMapper(),
|
||||
mock(SageMakerGpuResolver.class));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user