(local_dir,
hf_model_path,
compiled_dir,
model_dir="text_encoder",
torch_dtype=torch.float32,
bs=1,
exhaustive_tune=False,
fp16=False,
bf16=True)
| 200 | |
| 201 | |
| 202 | def get_clip_model(local_dir, |
| 203 | hf_model_path, |
| 204 | compiled_dir, |
| 205 | model_dir="text_encoder", |
| 206 | torch_dtype=torch.float32, |
| 207 | bs=1, |
| 208 | exhaustive_tune=False, |
| 209 | fp16=False, |
| 210 | bf16=True): |
| 211 | clip_local_dir = get_local_path(local_dir, model_dir) |
| 212 | onnx_file = "model.onnx" |
| 213 | onnx_path = os.path.join(clip_local_dir, onnx_file) |
| 214 | |
| 215 | def get_compiled_file_name(): |
| 216 | name = f"model_b{bs}" |
| 217 | if fp16: |
| 218 | name += "_fp16" |
| 219 | elif bf16: |
| 220 | name += "_bf16" |
| 221 | |
| 222 | if exhaustive_tune: name += "_exh" |
| 223 | return name + ".mxr" |
| 224 | |
| 225 | clip_compiled_dir = get_local_path(compiled_dir, model_dir) |
| 226 | mxr_file = get_compiled_file_name() |
| 227 | mxr_path = os.path.join(clip_compiled_dir, mxr_file) |
| 228 | |
| 229 | if os.path.isfile(mxr_path): |
| 230 | print(f"found compiled model.. loading CLIP encoder from {mxr_path}") |
| 231 | model = MGXModel(mxr_path) |
| 232 | return model |
| 233 | |
| 234 | sample_inputs = (torch.zeros(bs, 77, dtype=torch.int32), ) |
| 235 | input_names = ["input_ids"] |
| 236 | if not os.path.isfile(onnx_path): |
| 237 | print("ONNX file not found.. exporting CLIP encoder to ONNX") |
| 238 | model = CLIPTextModel.from_pretrained(hf_model_path, |
| 239 | subfolder=model_dir, |
| 240 | torch_dtype=torch_dtype) |
| 241 | |
| 242 | output_names = ["text_embeddings"] |
| 243 | dynamic_axes = {"input_ids": {0: 'B'}, "text_embeddings": {0: 'B'}} |
| 244 | |
| 245 | # CLIP export requires nightly pytorch due to bug in onnx parser |
| 246 | with torch.inference_mode(): |
| 247 | torch.onnx.export(model, |
| 248 | sample_inputs, |
| 249 | onnx_path, |
| 250 | export_params=True, |
| 251 | input_names=input_names, |
| 252 | output_names=output_names, |
| 253 | dynamic_axes=dynamic_axes) |
| 254 | |
| 255 | assert os.path.isfile(onnx_path) |
| 256 | print(f"Generating MXR from ONNX file: {onnx_path}") |
| 257 | input_shapes = { |
| 258 | n: list(t.size()) |
| 259 | for n, t in zip(input_names, sample_inputs) |
no test coverage detected