Skip to content
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

Convert huggingface model to onnx #1888

Merged
merged 4 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion serving/docker/lmi.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ ARG torch_version=2.1.2
ARG torch_vision_version=0.16.2
ARG onnx_version=1.17.1
ARG pydantic_version=2.6.1
ARG djl_converter_wheel="https://publish.djl.ai/djl_converter/djl_converter-0.28.0-py3-none-any.whl"
# HF Deps
ARG protobuf_version=3.20.3
ARG transformers_version=4.40.0
Expand Down Expand Up @@ -92,7 +93,9 @@ RUN pip3 install torch==${torch_version} torchvision==${torch_vision_version} --
transformers==${transformers_version} hf-transfer zstandard datasets==${datasets_version} \
mpi4py sentencepiece tiktoken blobfile einops accelerate==${accelerate_version} bitsandbytes==${bitsandbytes_version} \
optimum==${optimum_version} auto-gptq==${auto_gptq_version} pandas pyarrow jinja2 \
opencv-contrib-python-headless safetensors scipy && \
opencv-contrib-python-headless safetensors scipy onnx sentence_transformers \
onnxruntime-gpu==${onnx_version} --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/ && \
pip3 install ${djl_converter_wheel} --no-deps && \
pip3 cache purge

RUN pip3 install ${flash_attn_2_wheel} ${lmi_dist_wheel} ${vllm_wheel} pydantic==${pydantic_version} && \
Expand Down
79 changes: 77 additions & 2 deletions wlm/src/main/java/ai/djl/serving/wlm/LmiUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ static boolean isTrtLlmRollingBatch(Properties properties) {

static boolean needConvert(ModelInfo<?, ?> info) {
Properties properties = info.getProperties();
return isTrtLlmRollingBatch(info.getProperties())
|| properties.containsKey("trtllm_python_backend");
return isTrtLlmRollingBatch(properties) || properties.containsKey("trtllm_python_backend");
}

static void convertTrtLLM(ModelInfo<?, ?> info) throws IOException {
Expand Down Expand Up @@ -136,6 +135,82 @@ static void convertTrtLLM(ModelInfo<?, ?> info) throws IOException {
}
}

static void convertOnnxModel(ModelInfo<?, ?> info) throws IOException {
String prefix = info.prop.getProperty("option.modelName", "model");
if (Files.isRegularFile(info.modelDir.resolve(prefix + ".onnx"))
|| Files.isRegularFile(info.modelDir.resolve("model.onnx"))) {
return;
}

Path repo;
String modelId = null;
if (info.downloadDir != null) {
repo = info.downloadDir;
} else {
repo = info.modelDir;
modelId = info.prop.getProperty("option.model_id");
if (modelId != null && Files.isDirectory(Paths.get(modelId))) {
repo = Paths.get(modelId);
}
}

if (modelId == null) {
modelId = repo.toString();
}
info.modelUrl = convertOnnx(modelId).toUri().toURL().toString();
}

private static Path convertOnnx(String modelId) throws IOException {
logger.info("Converting model to onnx artifacts");
String hash = Utils.hash(modelId);
String download = Utils.getenv("SERVING_DOWNLOAD_DIR", null);
Path parent = download == null ? Utils.getCacheDir() : Paths.get(download);
Path repoDir = parent.resolve("onnx").resolve(hash);
if (Files.exists(repoDir)) {
logger.info("Onnx artifacts already converted: {}", repoDir);
return repoDir;
}

String[] cmd = {
"djl-convert",
"--output-dir",
repoDir.toAbsolutePath().toString(),
"--output-format",
"OnnxRuntime",
"-m",
modelId,
"--optimize",
CudaUtils.hasCuda() ? "O4" : "O2",
"--device",
CudaUtils.hasCuda() ? "cuda" : "cpu"
};
boolean success = false;
try {
Process exec = new ProcessBuilder(cmd).redirectErrorStream(true).start();
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(exec.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
logger.debug("convert: {}", line);
}
}
int exitCode = exec.waitFor();
if (0 != exitCode) {
throw new EngineException("Model conversion process failed!");
}
success = true;
logger.info("Onnx artifacts built successfully");
return repoDir;
} catch (InterruptedException e) {
throw new IOException("Failed to build TensorRT-LLM artifacts", e);
} finally {
if (!success) {
Utils.deleteQuietly(repoDir);
}
}
}

/**
* Returns the Huggingface config.json file URI.
*
Expand Down
9 changes: 9 additions & 0 deletions wlm/src/main/java/ai/djl/serving/wlm/ModelInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,16 @@ public void initialize() throws IOException, ModelException {
metric = new Metric("ConvertTrtllm", duration, Unit.MICROSECONDS, dimension);
MODEL_METRIC.info("{}", metric);
eventManager.onModelConverted(this, "trtllm");
} else if ("OnnxRuntime".equals(getEngineName())) {
eventManager.onModelConverting(this, "onnx");
begin = System.nanoTime();
LmiUtils.convertOnnxModel(this);
duration = (System.nanoTime() - begin) / 1000;
metric = new Metric("ConvertOnnx", duration, Unit.MICROSECONDS, dimension);
MODEL_METRIC.info("{}", metric);
eventManager.onModelConverted(this, "onnx");
}

// override prop keys are not write to serving.properties,
// we have to explicitly set in Criteria
if (options == null) {
Expand Down
2 changes: 2 additions & 0 deletions wlm/src/test/java/ai/djl/serving/wlm/ModelInfoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ public void testInitModel() throws IOException, ModelException {
Path onnx = modelDir.resolve("test_model.onnx");
Files.createFile(onnx);
model = new ModelInfo<>("build/models/test_model");
model.prop = new Properties();
model.prop.put("option.modelName", "test_model");
model.initialize();
assertEquals(model.getEngineName(), "OnnxRuntime");

Expand Down
Loading