Skip to content

Commit 3961096

Browse files
committed
feat(utils): add treemap, parameterization, workflow, profiling, and vision utilities
1 parent 602a197 commit 3961096

15 files changed

Lines changed: 5018 additions & 78 deletions

File tree

‎python/oxideon/__init__.py‎

Lines changed: 86 additions & 0 deletions
Large diffs are not rendered by default.

‎python/oxideon/__init__.pyi‎

Lines changed: 236 additions & 4 deletions
Large diffs are not rendered by default.

‎python/oxideon/data.py‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Dataset and DataLoader pipeline for Oxideon.
22
3-
Provides PyTorch-compatible `Dataset`, `TensorDataset`, `DataLoader`,
3+
Provides `Dataset`, `TensorDataset`, `DataLoader`, samplers,
44
and dataset splitting helpers (`random_split`).
55
"""
66

@@ -57,6 +57,27 @@ def __len__(self) -> int:
5757
return len(self.indices)
5858

5959

60+
def to_tensors(data: Any) -> Any:
61+
"""Recursively converts NumPy arrays and numeric scalars inside nested structures into Oxideon `Tensor`s
62+
without adding a batch dimension.
63+
"""
64+
if isinstance(data, Tensor):
65+
return data
66+
if isinstance(data, np.ndarray):
67+
if data.dtype.kind in ("S", "U", "O"):
68+
return data
69+
return Tensor.from_numpy(np.ascontiguousarray(data))
70+
if isinstance(data, (np.bool_, np.number)):
71+
return Tensor.from_numpy(np.asarray(data))
72+
if isinstance(data, tuple) and hasattr(data, "_fields"):
73+
return type(data)(*(to_tensors(d) for d in data))
74+
if isinstance(data, (tuple, list)):
75+
return type(data)(to_tensors(d) for d in data)
76+
if isinstance(data, dict):
77+
return {k: to_tensors(v) for k, v in data.items()}
78+
return data
79+
80+
6081
def default_collate(batch: List[Any]) -> Any:
6182
"""Collates a list of samples into a batch tensor or tuple of tensors."""
6283
if not batch:
@@ -593,4 +614,4 @@ def __len__(self) -> int:
593614
return self._length
594615

595616

596-
__all__ += ["DistributedSampler", "StackDataset"]
617+
__all__ += ["DistributedSampler", "StackDataset", "to_tensors"]

‎python/oxideon/func.py‎

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -262,33 +262,21 @@ def functional_call(
262262
parameter_and_buffer_dicts: Dict[str, Any],
263263
args: Any = (),
264264
kwargs: Optional[Dict[str, Any]] = None,
265+
*,
266+
tie_weights: bool = True,
267+
strict: bool = False,
265268
) -> Any:
266269
"""Invokes `module(*args, **kwargs)` with parameters temporarily substituted by `parameter_and_buffer_dicts`."""
267-
kwargs = kwargs or {}
268-
saved_attrs = {}
269-
270-
try:
271-
# Swap parameters/buffers
272-
for name, tensor_val in parameter_and_buffer_dicts.items():
273-
parts = name.split(".")
274-
curr = module
275-
for p in parts[:-1]:
276-
curr = getattr(curr, p)
277-
last_part = parts[-1]
278-
if hasattr(curr, last_part):
279-
saved_attrs[name] = getattr(curr, last_part)
280-
setattr(curr, last_part, tensor_val)
281-
282-
return module(*args, **kwargs)
283-
finally:
284-
# Restore original parameters/buffers
285-
for name, orig_val in saved_attrs.items():
286-
parts = name.split(".")
287-
curr = module
288-
for p in parts[:-1]:
289-
curr = getattr(curr, p)
290-
last_part = parts[-1]
291-
setattr(curr, last_part, orig_val)
270+
from .nn_utils import apply_with_weights
271+
272+
return apply_with_weights(
273+
module,
274+
parameter_and_buffer_dicts,
275+
args=args,
276+
kwargs=kwargs,
277+
tie_weights=tie_weights,
278+
strict=strict,
279+
)
292280

293281

294282
def make_functional(module: Any) -> Tuple[Callable[..., Any], Dict[str, Any]]:

‎python/oxideon/nn.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,12 @@ def __init__(self, hooks_dict):
181181
def remove(self):
182182
self.hooks_dict.pop(self.id, None)
183183

184+
def __enter__(self):
185+
return self
186+
187+
def __exit__(self, exc_type, exc_val, exc_tb):
188+
self.remove()
189+
184190

185191
# ---------------------------------------------------------------------------
186192
# Base Module Class

0 commit comments

Comments
 (0)