Skip to content

Commit

Permalink
Basic functioning library with CI
Browse files Browse the repository at this point in the history
  • Loading branch information
ArvinSKushwaha committed Jun 4, 2024
1 parent f4557cd commit 4404b05
Show file tree
Hide file tree
Showing 10 changed files with 551 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: CI
on: ['push', 'pull_request']
jobs:
build_and_test:
name: Build and Test
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]

steps:
- uses: actions/checkout@v4

- name: Rye
uses: eifinger/setup-rye@v3
with:
version: 'latest'
enable-cache: true
github-token: ${{ secrets.GITHUB_TOKEN }}

- name: Test
run: rye test
10 changes: 10 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
MIT License

Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

35 changes: 35 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
[project]
name = "jaximal"
version = "0.1.0"
description = "Add your description here"
authors = [
{ name = "Arvin Kushwaha", email = "[email protected]" }
]
dependencies = [
"safetensors>=0.4.3",
"jaxtyping>=0.2.29",
"jax>=0.4.28",
"optax>=0.2.2",
"jaxlib>=0.4.28",
]
readme = "README.md"
requires-python = ">= 3.12"
license = { text = "MIT" }

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.rye]
managed = true
dev-dependencies = [
"pytest>=8.2.1",
]
excluded-dependencies = [
]

[tool.hatch.metadata]
allow-direct-references = true

[tool.hatch.build.targets.wheel]
packages = ["src/jaximal"]
60 changes: 60 additions & 0 deletions requirements-dev.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# generated by rye
# use `rye lock` or `rye sync` to update this lockfile
#
# last locked with the following flags:
# pre: false
# features: []
# all-features: false
# with-sources: false

-e file:.
absl-py==2.1.0
# via chex
# via optax
chex==0.1.86
# via optax
iniconfig==2.0.0
# via pytest
jax==0.4.28
# via chex
# via jaximal
# via optax
jaxlib==0.4.28
# via chex
# via jaximal
# via optax
jaxtyping==0.2.29
# via jaximal
ml-dtypes==0.4.0
# via jax
# via jaxlib
numpy==1.26.4
# via chex
# via jax
# via jaxlib
# via ml-dtypes
# via opt-einsum
# via optax
# via scipy
opt-einsum==3.3.0
# via jax
optax==0.2.2
# via jaximal
packaging==24.0
# via pytest
pluggy==1.5.0
# via pytest
pytest==8.2.1
safetensors==0.4.3
# via jaximal
scipy==1.13.1
# via jax
# via jaxlib
setuptools==70.0.0
# via chex
toolz==0.12.1
# via chex
typeguard==2.13.3
# via jaxtyping
typing-extensions==4.12.1
# via chex
53 changes: 53 additions & 0 deletions requirements.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# generated by rye
# use `rye lock` or `rye sync` to update this lockfile
#
# last locked with the following flags:
# pre: false
# features: []
# all-features: false
# with-sources: false

-e file:.
absl-py==2.1.0
# via chex
# via optax
chex==0.1.86
# via optax
jax==0.4.28
# via chex
# via jaximal
# via optax
jaxlib==0.4.28
# via chex
# via jaximal
# via optax
jaxtyping==0.2.29
# via jaximal
ml-dtypes==0.4.0
# via jax
# via jaxlib
numpy==1.26.4
# via chex
# via jax
# via jaxlib
# via ml-dtypes
# via opt-einsum
# via optax
# via scipy
opt-einsum==3.3.0
# via jax
optax==0.2.2
# via jaximal
safetensors==0.4.3
# via jaximal
scipy==1.13.1
# via jax
# via jaxlib
setuptools==70.0.0
# via chex
toolz==0.12.1
# via chex
typeguard==2.13.3
# via jaxtyping
typing-extensions==4.12.1
# via chex
1 change: 1 addition & 0 deletions src/jaximal/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import core
176 changes: 176 additions & 0 deletions src/jaximal/core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import jax
import typing

from dataclasses import make_dataclass
from .typing import Array, AbstractArray
from typing import (
Annotated,
Any,
Mapping,
Sequence,
dataclass_transform,
get_origin,
)
from json import dumps, loads


type Static[T] = Annotated[T, "jaximal::meta"]


@dataclass_transform(eq_default=True, frozen_default=True)
class Jaximal:
def __init_subclass__(cls) -> None:
cls2 = make_dataclass(
cls.__name__, list(cls.__annotations__), slots=True, frozen=True
)
cls.__init__ = cls2.__init__ # pyright: ignore
cls.__repr__ = cls2.__repr__ # pyright: ignore
cls.__slots__ = cls2.__slots__ # pyright: ignore
cls.__setattr__ = cls2.__setattr__ # pyright: ignore
cls.__delattr__ = cls2.__delattr__ # pyright: ignore
cls.__getattribute__ = cls2.__getattribute__ # pyright: ignore

data_fields = [
key for key, typ in cls.__annotations__.items() if get_origin(typ) != Static
]
meta_fields = [
key for key, typ in cls.__annotations__.items() if get_origin(typ) == Static
]

jax.tree_util.register_dataclass(cls, data_fields, meta_fields)

def cls_eq(self, other: object) -> bool:
if type(other) != type(self): return False

equal = True
for meta in meta_fields:
equal &= getattr(self, meta) == getattr(other, meta)

if not equal:
return False

for data in data_fields:
if (ann := cls.__annotations__[data]) == Array or issubclass(ann, AbstractArray):
equal &= (getattr(self, data) == getattr(other, data)).all()
else:
equal &= getattr(self, data) == getattr(other, data)

if not equal:
return False

return equal

cls.__eq__ = cls_eq


def dictify(
x: Any,
prefix: str = "",
typ: type | None = None,
) -> tuple[dict[str, Array], dict[str, str]]:
typ = type(x) if typ is None else typ

data: dict[str, Array] = {}
meta: dict[str, str] = {}

if get_origin(typ) == Static:
meta |= {prefix.removesuffix("::"): dumps(x)}

elif isinstance(x, Array):
data |= {prefix.removesuffix("::"): x}

elif issubclass(typ, Jaximal):
for child_key, child_type in x.__annotations__.items():
child_data, child_meta = dictify(
getattr(x, child_key), prefix + child_key + "::", typ=child_type
)

data |= child_data
meta |= child_meta

elif isinstance(x, Sequence):
for child_idx, child_elem in enumerate(x):
child_data, child_meta = dictify(child_elem, prefix + str(child_idx) + "::")

data |= child_data
meta |= child_meta

elif isinstance(x, Mapping):
for child_key, child_elem in x.items():
child_data, child_meta = dictify(child_elem, prefix + str(child_key) + "::")

data |= child_data
meta |= child_meta

else:
raise TypeError(
f"Unexpected type {typ} and prefix {prefix} recieved by `dictify`."
)

return data, meta


def dedictify[T](
typ: type[T],
data: dict[str, Array],
meta: dict[str, str],
prefix: str = "",
) -> T:
base_typ = get_origin(typ)
if base_typ is None:
base_typ = typ

if get_origin(typ) == Static:
return loads(meta[prefix.removesuffix("::")])

elif typ == Array or issubclass(base_typ, AbstractArray):
return data[prefix.removesuffix("::")] # type: ignore

elif issubclass(base_typ, Jaximal):
children = {}
for child_key, child_type in typ.__annotations__.items():
children[child_key] = dedictify(
child_type, data, meta, prefix + child_key + "::"
)

return typ(**children)

elif issubclass(base_typ, list):
children = []
(child_type,) = typing.get_args(typ)

child_idx = 0
while True:
child_prefix = prefix + str(child_idx) + "::"
try:
next(filter(lambda x: x.startswith(child_prefix), data))
next(filter(lambda x: x.startswith(child_prefix), meta))
except StopIteration:
break
children.append(dedictify(child_type, data, meta, child_prefix))
child_idx += 1

return children # type: ignore

elif issubclass(base_typ, Mapping):
children = {}
key_type, child_type = typing.get_args(typ)

for keys in filter(lambda x: x.startswith(prefix), data):
keys = keys[len(prefix) :]
child_key = key_type(keys.split("::", 1)[0])
child_prefix = prefix + str(child_key) + "::"

if child_key in children:
continue

children[child_key] = dedictify(child_type, data, meta, child_prefix)

return children # type: ignore

raise TypeError(
f"Unexpected type {typ} and prefix {prefix} recieved by `dedictify`."
)


__all__ = ["Jaximal", "Static", "dictify"]
34 changes: 34 additions & 0 deletions src/jaximal/io.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from pathlib import Path
import safetensors.flax as safflax
import json
import struct

from .typing import Array


def save_file(filename: Path | str, data: dict[str, Array], meta: dict[str,
str]):
safflax.save_file(data, filename, meta)


def load_file(filename: Path | str) -> tuple[dict[str, Array], dict[str, str]]:
data = safflax.load_file(filename)

with open(filename, "rb") as f:
header_len = struct.unpack('<Q', f.read(8))[0]
meta = json.loads(f.read(header_len))['__metadata__']

return data, meta


def save(data: dict[str, Array], meta: dict[str, str]) -> bytes:
return safflax.save(data, meta)


def load(raw_data: bytes) -> tuple[dict[str, Array], dict[str, str]]:
data = safflax.load(raw_data)

header_len = struct.unpack('<Q', raw_data[:8])[0]
meta = json.loads(raw_data[8:8 + header_len])['__metadata__']

return data, meta
Loading

0 comments on commit 4404b05

Please sign in to comment.