MogensR commited on
Commit
bb1a40e
·
1 Parent(s): 52c1994

Create early_env.py

Browse files
Files changed (1) hide show
  1. early_env.py +30 -0
early_env.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # early_env.py — import this BEFORE numpy/torch/cv2/etc.
2
+ import os, re
3
+
4
+ def _clean_int_env(name: str, default: str | None = None):
5
+ val = os.environ.get(name)
6
+ if val is None:
7
+ if default is not None:
8
+ os.environ[name] = default
9
+ return
10
+ if not re.fullmatch(r"\d+", str(val).strip()):
11
+ if default is None:
12
+ os.environ.pop(name, None)
13
+ else:
14
+ os.environ[name] = default
15
+
16
+ # Keep thread env sane for Spaces (prevents libgomp errors)
17
+ _clean_int_env("OMP_NUM_THREADS", "2")
18
+ _clean_int_env("MKL_NUM_THREADS", "2")
19
+ _clean_int_env("OPENBLAS_NUM_THREADS", "2")
20
+ _clean_int_env("NUMEXPR_NUM_THREADS", "2")
21
+
22
+ # Configure PyTorch threading EARLY (before any parallel work)
23
+ try:
24
+ import torch
25
+ if hasattr(torch, "set_num_interop_threads"):
26
+ torch.set_num_interop_threads(2)
27
+ if hasattr(torch, "set_num_threads"):
28
+ torch.set_num_threads(2)
29
+ except Exception:
30
+ pass