Spaces:
Sleeping
Sleeping
Commit ·
961a8e6
1
Parent(s): c3678cb
Switch to bert-tiny - fits in 512MB RAM
Browse files- app/inference.py +30 -36
- download_model.py +3 -3
app/inference.py
CHANGED
|
@@ -1,18 +1,15 @@
|
|
| 1 |
-
import time, os, gc
|
| 2 |
-
import numpy as np
|
| 3 |
from pathlib import Path
|
| 4 |
|
| 5 |
MODEL_DIR = Path("models")
|
| 6 |
ONNX_PATH = MODEL_DIR / "model.onnx"
|
| 7 |
QUANTIZED_PATH = MODEL_DIR / "model_quantized.onnx"
|
| 8 |
-
MODEL_NAME = "
|
| 9 |
_tokenizer = None
|
| 10 |
|
| 11 |
def _get_file_size_mb(path) -> float:
|
| 12 |
-
try:
|
| 13 |
-
|
| 14 |
-
except:
|
| 15 |
-
return 0.0
|
| 16 |
|
| 17 |
def _load_tokenizer():
|
| 18 |
global _tokenizer
|
|
@@ -30,10 +27,8 @@ def _export_to_onnx():
|
|
| 30 |
if not ONNX_PATH.exists():
|
| 31 |
import shutil
|
| 32 |
for f in MODEL_DIR.glob("*.onnx"):
|
| 33 |
-
shutil.copy(str(f), str(ONNX_PATH))
|
| 34 |
-
|
| 35 |
-
del model
|
| 36 |
-
gc.collect()
|
| 37 |
|
| 38 |
def _quantize_onnx():
|
| 39 |
if not QUANTIZED_PATH.exists():
|
|
@@ -41,26 +36,25 @@ def _quantize_onnx():
|
|
| 41 |
from onnxruntime.quantization import quantize_dynamic, QuantType
|
| 42 |
quantize_dynamic(str(ONNX_PATH), str(QUANTIZED_PATH), weight_type=QuantType.QInt8)
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
|
| 46 |
-
inputs =
|
| 47 |
feed = {k: v for k, v in inputs.items() if k in [i.name for i in session.get_inputs()]}
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
label_idx = int(np.argmax(probs))
|
| 53 |
-
return {"label": ["NEGATIVE", "POSITIVE"][label_idx], "confidence": round(float(probs[label_idx]), 4)}
|
| 54 |
|
| 55 |
def run_baseline(text):
|
| 56 |
from transformers import pipeline
|
| 57 |
-
pipe = pipeline("
|
| 58 |
start = time.perf_counter()
|
| 59 |
result = pipe(text)[0]
|
| 60 |
-
latency = (time.perf_counter()
|
| 61 |
del pipe; gc.collect()
|
| 62 |
-
|
| 63 |
-
|
|
|
|
| 64 |
|
| 65 |
def run_onnx(text):
|
| 66 |
import onnxruntime as ort
|
|
@@ -68,11 +62,11 @@ def run_onnx(text):
|
|
| 68 |
opts = ort.SessionOptions(); opts.intra_op_num_threads = 1
|
| 69 |
session = ort.InferenceSession(str(ONNX_PATH), sess_options=opts)
|
| 70 |
start = time.perf_counter()
|
| 71 |
-
|
| 72 |
-
latency = (time.perf_counter()
|
| 73 |
del session; gc.collect()
|
| 74 |
-
return {**
|
| 75 |
-
"model_size_mb": _get_file_size_mb(ONNX_PATH) or
|
| 76 |
|
| 77 |
def run_quantized(text):
|
| 78 |
import onnxruntime as ort
|
|
@@ -80,14 +74,14 @@ def run_quantized(text):
|
|
| 80 |
opts = ort.SessionOptions(); opts.intra_op_num_threads = 1
|
| 81 |
session = ort.InferenceSession(str(QUANTIZED_PATH), sess_options=opts)
|
| 82 |
start = time.perf_counter()
|
| 83 |
-
|
| 84 |
-
latency = (time.perf_counter()
|
| 85 |
del session; gc.collect()
|
| 86 |
-
return {**
|
| 87 |
-
"model_size_mb": _get_file_size_mb(QUANTIZED_PATH) or
|
| 88 |
|
| 89 |
def run_all_models(text):
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
return {"baseline":
|
|
|
|
| 1 |
+
import time, os, gc, numpy as np
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
|
| 4 |
MODEL_DIR = Path("models")
|
| 5 |
ONNX_PATH = MODEL_DIR / "model.onnx"
|
| 6 |
QUANTIZED_PATH = MODEL_DIR / "model_quantized.onnx"
|
| 7 |
+
MODEL_NAME = "prajjwal1/bert-tiny"
|
| 8 |
_tokenizer = None
|
| 9 |
|
| 10 |
def _get_file_size_mb(path) -> float:
|
| 11 |
+
try: return round(os.path.getsize(path) / (1024*1024), 1)
|
| 12 |
+
except: return 0.0
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def _load_tokenizer():
|
| 15 |
global _tokenizer
|
|
|
|
| 27 |
if not ONNX_PATH.exists():
|
| 28 |
import shutil
|
| 29 |
for f in MODEL_DIR.glob("*.onnx"):
|
| 30 |
+
shutil.copy(str(f), str(ONNX_PATH)); break
|
| 31 |
+
del model; gc.collect()
|
|
|
|
|
|
|
| 32 |
|
| 33 |
def _quantize_onnx():
|
| 34 |
if not QUANTIZED_PATH.exists():
|
|
|
|
| 36 |
from onnxruntime.quantization import quantize_dynamic, QuantType
|
| 37 |
quantize_dynamic(str(ONNX_PATH), str(QUANTIZED_PATH), weight_type=QuantType.QInt8)
|
| 38 |
|
| 39 |
+
def _onnx_infer(session, text):
|
| 40 |
+
tok = _load_tokenizer()
|
| 41 |
+
inputs = tok(text, return_tensors="np", truncation=True, max_length=128, padding=True)
|
| 42 |
feed = {k: v for k, v in inputs.items() if k in [i.name for i in session.get_inputs()]}
|
| 43 |
+
out = session.run(None, feed)[0][0]
|
| 44 |
+
exp = np.exp(out - np.max(out)); probs = exp / exp.sum()
|
| 45 |
+
idx = int(np.argmax(probs))
|
| 46 |
+
return {"label": ["NEGATIVE","POSITIVE"][idx], "confidence": round(float(probs[idx]),4)}
|
|
|
|
|
|
|
| 47 |
|
| 48 |
def run_baseline(text):
|
| 49 |
from transformers import pipeline
|
| 50 |
+
pipe = pipeline("text-classification", model=MODEL_NAME, device=-1)
|
| 51 |
start = time.perf_counter()
|
| 52 |
result = pipe(text)[0]
|
| 53 |
+
latency = (time.perf_counter()-start)*1000
|
| 54 |
del pipe; gc.collect()
|
| 55 |
+
label = "POSITIVE" if result["label"] == "LABEL_1" else "NEGATIVE"
|
| 56 |
+
return {"label": label, "confidence": round(result["score"],4),
|
| 57 |
+
"latency_ms": round(latency,2), "model_size_mb": 17.0, "format": "PyTorch (.bin)"}
|
| 58 |
|
| 59 |
def run_onnx(text):
|
| 60 |
import onnxruntime as ort
|
|
|
|
| 62 |
opts = ort.SessionOptions(); opts.intra_op_num_threads = 1
|
| 63 |
session = ort.InferenceSession(str(ONNX_PATH), sess_options=opts)
|
| 64 |
start = time.perf_counter()
|
| 65 |
+
pred = _onnx_infer(session, text)
|
| 66 |
+
latency = (time.perf_counter()-start)*1000
|
| 67 |
del session; gc.collect()
|
| 68 |
+
return {**pred, "latency_ms": round(latency,2),
|
| 69 |
+
"model_size_mb": _get_file_size_mb(ONNX_PATH) or 17.0, "format": "ONNX (.onnx)"}
|
| 70 |
|
| 71 |
def run_quantized(text):
|
| 72 |
import onnxruntime as ort
|
|
|
|
| 74 |
opts = ort.SessionOptions(); opts.intra_op_num_threads = 1
|
| 75 |
session = ort.InferenceSession(str(QUANTIZED_PATH), sess_options=opts)
|
| 76 |
start = time.perf_counter()
|
| 77 |
+
pred = _onnx_infer(session, text)
|
| 78 |
+
latency = (time.perf_counter()-start)*1000
|
| 79 |
del session; gc.collect()
|
| 80 |
+
return {**pred, "latency_ms": round(latency,2),
|
| 81 |
+
"model_size_mb": _get_file_size_mb(QUANTIZED_PATH) or 4.5, "format": "Quantized ONNX INT8 (.onnx)"}
|
| 82 |
|
| 83 |
def run_all_models(text):
|
| 84 |
+
b = run_baseline(text); gc.collect()
|
| 85 |
+
o = run_onnx(text); gc.collect()
|
| 86 |
+
q = run_quantized(text); gc.collect()
|
| 87 |
+
return {"baseline": b, "onnx": o, "quantized": q}
|
download_model.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 2 |
-
MODEL = "
|
| 3 |
print("Downloading tokenizer...")
|
| 4 |
AutoTokenizer.from_pretrained(MODEL)
|
| 5 |
-
print("Downloading
|
| 6 |
AutoModelForSequenceClassification.from_pretrained(MODEL)
|
| 7 |
-
print("
|
|
|
|
| 1 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 2 |
+
MODEL = "prajjwal1/bert-tiny"
|
| 3 |
print("Downloading tokenizer...")
|
| 4 |
AutoTokenizer.from_pretrained(MODEL)
|
| 5 |
+
print("Downloading model...")
|
| 6 |
AutoModelForSequenceClassification.from_pretrained(MODEL)
|
| 7 |
+
print("Done!")
|