-
Notifications
You must be signed in to change notification settings - Fork 25.3k
[ML] Integrate SageMaker with OpenAI Embeddings #126856
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
acdca34
sagemaker
prwhelan 350cc3a
Update docs/changelog/126856.yaml
prwhelan f4ddb12
[CI] Auto commit changes from spotless
elasticsearchmachine 01eaabd
more tests; address comments
prwhelan 761d2ef
Merge branch 'main' into sagemaker
prwhelan f60d951
add transportversion, javadocs
prwhelan 14b358e
[CI] Auto commit changes from spotless
elasticsearchmachine 204bc9f
Remove forbidden API
prwhelan 0ece5f9
[CI] Auto commit changes from spotless
elasticsearchmachine 9901353
Remove forbidden API in tests
prwhelan 1f519d8
Add more error handling; fix bugs with OpenAi; Configuration
prwhelan 77f3a45
Merge branch 'main' into sagemaker
prwhelan e9edfd4
Merge branch 'main' into sagemaker
prwhelan 68ebae7
Update dimensionsSetByUser when dimensions are taken from validate re…
prwhelan 057797c
Drop dimensions when it isn't set by users
prwhelan 4f8f41c
Merge branch 'main' into sagemaker
prwhelan 07b8680
Merge branch 'main' into sagemaker
prwhelan abaa9cb
Merge branch 'main' into sagemaker
prwhelan 8ea40bb
Address comments
prwhelan 21f5bca
Merge branch 'main' into sagemaker
prwhelan 19ab2d2
Merge branch 'main' into sagemaker
prwhelan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
pr: 126856 | ||
summary: "[Draft][Not For Checkin] Current `SageMaker` work" | ||
area: Machine Learning | ||
type: enhancement | ||
issues: [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
186 changes: 186 additions & 0 deletions
186
...e/src/main/java/org/elasticsearch/xpack/inference/services/sagemaker/SageMakerClient.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,186 @@ | ||||||
/* | ||||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||||||
* or more contributor license agreements. Licensed under the Elastic License | ||||||
* 2.0; you may not use this file except in compliance with the Elastic License | ||||||
* 2.0. | ||||||
*/ | ||||||
|
||||||
package org.elasticsearch.xpack.inference.services.sagemaker; | ||||||
|
||||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; | ||||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; | ||||||
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; | ||||||
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; | ||||||
import software.amazon.awssdk.profiles.ProfileFile; | ||||||
import software.amazon.awssdk.regions.Region; | ||||||
import software.amazon.awssdk.services.sagemakerruntime.SageMakerRuntimeAsyncClient; | ||||||
import software.amazon.awssdk.services.sagemakerruntime.model.InvokeEndpointRequest; | ||||||
import software.amazon.awssdk.services.sagemakerruntime.model.InvokeEndpointResponse; | ||||||
import software.amazon.awssdk.services.sagemakerruntime.model.InvokeEndpointWithResponseStreamRequest; | ||||||
import software.amazon.awssdk.services.sagemakerruntime.model.InvokeEndpointWithResponseStreamResponse; | ||||||
import software.amazon.awssdk.services.sagemakerruntime.model.InvokeEndpointWithResponseStreamResponseHandler; | ||||||
import software.amazon.awssdk.services.sagemakerruntime.model.ResponseStream; | ||||||
|
||||||
import org.apache.logging.log4j.LogManager; | ||||||
import org.apache.logging.log4j.Logger; | ||||||
import org.elasticsearch.ElasticsearchException; | ||||||
import org.elasticsearch.ExceptionsHelper; | ||||||
import org.elasticsearch.SpecialPermission; | ||||||
import org.elasticsearch.action.ActionListener; | ||||||
import org.elasticsearch.common.cache.Cache; | ||||||
import org.elasticsearch.common.cache.CacheBuilder; | ||||||
import org.elasticsearch.common.cache.CacheLoader; | ||||||
import org.elasticsearch.core.TimeValue; | ||||||
import org.elasticsearch.core.Tuple; | ||||||
import org.elasticsearch.threadpool.ThreadPool; | ||||||
import org.elasticsearch.xpack.inference.common.amazon.AwsSecretSettings; | ||||||
import org.elasticsearch.xpack.inference.external.http.HttpSettings; | ||||||
import org.reactivestreams.FlowAdapters; | ||||||
|
||||||
import java.io.Closeable; | ||||||
import java.security.AccessController; | ||||||
import java.security.PrivilegedExceptionAction; | ||||||
import java.util.concurrent.ExecutionException; | ||||||
import java.util.concurrent.Flow; | ||||||
import java.util.concurrent.TimeUnit; | ||||||
import java.util.concurrent.atomic.AtomicReference; | ||||||
|
||||||
import static org.elasticsearch.xpack.inference.InferencePlugin.UTILITY_THREAD_POOL_NAME; | ||||||
|
||||||
public class SageMakerClient implements Closeable { | ||||||
private static final Logger log = LogManager.getLogger(SageMakerClient.class); | ||||||
private final Cache<RegionAndSecrets, SageMakerRuntimeAsyncClient> existingClients = CacheBuilder.< | ||||||
RegionAndSecrets, | ||||||
SageMakerRuntimeAsyncClient>builder() | ||||||
.removalListener(removal -> removal.getValue().close()) | ||||||
.setExpireAfterAccess(TimeValue.timeValueMinutes(15)) | ||||||
.build(); | ||||||
|
||||||
private final CacheLoader<RegionAndSecrets, SageMakerRuntimeAsyncClient> clientFactory; | ||||||
private final ThreadPool threadPool; | ||||||
|
||||||
public SageMakerClient(CacheLoader<RegionAndSecrets, SageMakerRuntimeAsyncClient> clientFactory, ThreadPool threadPool) { | ||||||
this.clientFactory = clientFactory; | ||||||
this.threadPool = threadPool; | ||||||
} | ||||||
|
||||||
public void invoke( | ||||||
RegionAndSecrets regionAndSecrets, | ||||||
InvokeEndpointRequest request, | ||||||
TimeValue timeout, | ||||||
ActionListener<InvokeEndpointResponse> listener | ||||||
) { | ||||||
var asyncClient = getOrCreateClient(regionAndSecrets); | ||||||
asyncClient.invokeEndpoint(request) | ||||||
.orTimeout(timeout.seconds(), TimeUnit.SECONDS) | ||||||
.thenAcceptAsync(listener::onResponse, threadPool.executor(UTILITY_THREAD_POOL_NAME)) | ||||||
.exceptionallyAsync(t -> failAndMaybeThrowError(t, listener), threadPool.executor(UTILITY_THREAD_POOL_NAME)); | ||||||
} | ||||||
|
||||||
private Void failAndMaybeThrowError(Throwable t, ActionListener<?> listener) { | ||||||
if (t instanceof Exception e) { | ||||||
listener.onFailure(e); | ||||||
} else { | ||||||
ExceptionsHelper.maybeError(t).ifPresent(ExceptionsHelper::maybeDieOnAnotherThread); | ||||||
log.atWarn().withThrowable(t).log("Unknown failure calling SageMaker."); | ||||||
listener.onFailure(new RuntimeException("Unknown failure calling SageMaker.")); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
} | ||||||
return null; // Void | ||||||
} | ||||||
|
||||||
public void invokeStream( | ||||||
RegionAndSecrets regionAndSecrets, | ||||||
InvokeEndpointWithResponseStreamRequest request, | ||||||
TimeValue timeout, | ||||||
ActionListener<SageMakerStream> listener | ||||||
) { | ||||||
var asyncClient = getOrCreateClient(regionAndSecrets); | ||||||
var runOnceListener = ActionListener.notifyOnce(listener); | ||||||
var responseStreamProcessor = new SageMakerStreamingResponseProcessor(); | ||||||
var responseStreamListener = InvokeEndpointWithResponseStreamResponseHandler.builder() | ||||||
.onResponse(response -> runOnceListener.onResponse(new SageMakerStream(response, responseStreamProcessor))) | ||||||
.onEventStream(publisher -> responseStreamProcessor.setPublisher(FlowAdapters.toFlowPublisher(publisher))) | ||||||
.build(); | ||||||
asyncClient.invokeEndpointWithResponseStream(request, responseStreamListener) | ||||||
.orTimeout(timeout.seconds(), TimeUnit.SECONDS) | ||||||
.exceptionallyAsync(t -> failAndMaybeThrowError(t, runOnceListener), threadPool.executor(UTILITY_THREAD_POOL_NAME)); | ||||||
} | ||||||
|
||||||
private SageMakerRuntimeAsyncClient getOrCreateClient(RegionAndSecrets regionAndSecrets) { | ||||||
try { | ||||||
return existingClients.computeIfAbsent(regionAndSecrets, clientFactory); | ||||||
} catch (ExecutionException e) { | ||||||
throw new ElasticsearchException("failed to create SageMakerRuntime client", e); | ||||||
prwhelan marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
} | ||||||
} | ||||||
|
||||||
@Override | ||||||
public void close() { | ||||||
existingClients.invalidateAll(); // will close each cached client | ||||||
} | ||||||
|
||||||
public record RegionAndSecrets(String region, AwsSecretSettings secretSettings) {} | ||||||
|
||||||
public static class Factory implements CacheLoader<RegionAndSecrets, SageMakerRuntimeAsyncClient> { | ||||||
private final HttpSettings httpSettings; | ||||||
|
||||||
public Factory(HttpSettings httpSettings) { | ||||||
this.httpSettings = httpSettings; | ||||||
} | ||||||
|
||||||
@Override | ||||||
public SageMakerRuntimeAsyncClient load(RegionAndSecrets key) throws Exception { | ||||||
SpecialPermission.check(); | ||||||
// TODO migrate to entitlements | ||||||
return AccessController.doPrivileged((PrivilegedExceptionAction<SageMakerRuntimeAsyncClient>) () -> { | ||||||
try (var accessKey = key.secretSettings().accessKey(); var secretKey = key.secretSettings().secretKey()) { | ||||||
var credentials = AwsBasicCredentials.create(accessKey.toString(), secretKey.toString()); | ||||||
var credentialsProvider = StaticCredentialsProvider.create(credentials); | ||||||
var clientConfig = NettyNioAsyncHttpClient.builder().connectionTimeout(httpSettings.connectionTimeoutDuration()); | ||||||
var override = ClientOverrideConfiguration.builder() | ||||||
// disable profileFile, user credentials will always come from the configured Model Secrets | ||||||
.defaultProfileFileSupplier(ProfileFile.aggregator()::build) | ||||||
.defaultProfileFile(ProfileFile.aggregator().build()) | ||||||
.retryPolicy(retryPolicy -> retryPolicy.numRetries(3)) | ||||||
.retryStrategy(retryStrategy -> retryStrategy.maxAttempts(3)) | ||||||
.build(); | ||||||
return SageMakerRuntimeAsyncClient.builder() | ||||||
.credentialsProvider(credentialsProvider) | ||||||
.region(Region.of(key.region())) | ||||||
.httpClientBuilder(clientConfig) | ||||||
.overrideConfiguration(override) | ||||||
.build(); | ||||||
} | ||||||
}); | ||||||
} | ||||||
} | ||||||
|
||||||
private static class SageMakerStreamingResponseProcessor implements Flow.Publisher<ResponseStream> { | ||||||
private static final Logger log = LogManager.getLogger(SageMakerStreamingResponseProcessor.class); | ||||||
private final AtomicReference<Tuple<Flow.Publisher<ResponseStream>, Flow.Subscriber<? super ResponseStream>>> holder = | ||||||
new AtomicReference<>(null); | ||||||
|
||||||
@Override | ||||||
public void subscribe(Flow.Subscriber<? super ResponseStream> subscriber) { | ||||||
if (holder.compareAndSet(null, Tuple.tuple(null, subscriber)) == false) { | ||||||
log.debug("Subscriber connecting to publisher."); | ||||||
var publisher = holder.getAndSet(null).v1(); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Other implementations of this method call |
||||||
publisher.subscribe(subscriber); | ||||||
} else { | ||||||
log.debug("Subscriber waiting for connection."); | ||||||
} | ||||||
} | ||||||
|
||||||
private void setPublisher(Flow.Publisher<ResponseStream> publisher) { | ||||||
if (holder.compareAndSet(null, Tuple.tuple(publisher, null)) == false) { | ||||||
log.debug("Publisher connecting to subscriber."); | ||||||
var subscriber = holder.getAndSet(null).v2(); | ||||||
publisher.subscribe(subscriber); | ||||||
} else { | ||||||
log.debug("Publisher waiting for connection."); | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
public record SageMakerStream(InvokeEndpointWithResponseStreamResponse response, Flow.Publisher<ResponseStream> responseStream) {} | ||||||
} |
22 changes: 22 additions & 0 deletions
22
.../java/org/elasticsearch/xpack/inference/services/sagemaker/SageMakerInferenceRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License | ||
* 2.0; you may not use this file except in compliance with the Elastic License | ||
* 2.0. | ||
*/ | ||
|
||
package org.elasticsearch.xpack.inference.services.sagemaker; | ||
|
||
import org.elasticsearch.core.Nullable; | ||
import org.elasticsearch.inference.InputType; | ||
|
||
import java.util.List; | ||
|
||
public record SageMakerInferenceRequest( | ||
String query, | ||
@Nullable Boolean returnDocuments, | ||
@Nullable Integer topN, | ||
@Nullable List<String> input, | ||
boolean stream, | ||
InputType inputType | ||
) {} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.