Metadata-Version: 2.4
Name: grilly2
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Environment :: GPU
Requires-Dist: numpy
Requires-Dist: tokenizers ; extra == 'huggingface'
Requires-Dist: safetensors ; extra == 'huggingface'
Requires-Dist: pytest ; extra == 'test'
Requires-Dist: torch ; extra == 'test'
Provides-Extra: huggingface
Provides-Extra: test
License-File: LICENSE
Summary: The torch API on Vulkan, for the GPUs torch will not train on
Keywords: pytorch,vulkan,gpu,amd,intel,inference,autograd
Author: Grill cheese
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/Grillcheese-AI/grilly2
Project-URL: Issues, https://github.com/Grillcheese-AI/grilly2/issues
Project-URL: Source, https://github.com/Grillcheese-AI/grilly2

# grilly2

The torch API on Vulkan, for the GPUs torch will not train on — consumer AMD and
Intel cards, and Windows. Early work; see `CLAUDE.md` for the plan and
`docs/boundary.md` for how the core talks to the GPU.

## Installing

```
pip install grilly2
```

Nothing else. No Rust, no C++ compiler, no Vulkan SDK — those are build
dependencies and they are spent on a CI runner, not on your machine. What you
need at runtime is a GPU driver with a Vulkan 1.2 device, which your driver
already installs.

**The package is `grilly2`; the import is `grilly`.** `grilly` on PyPI is v1,
a different project. The two both own a top-level `grilly` package, so pip
will let you install both and silently let one overwrite the other — if v1 is
there, `pip uninstall grilly` first.

If anything is wrong:

```
grilly-doctor          # or: python -m grilly.doctor
```

It prints which interpreter, which install and which device, then runs a real
kernel. Paste all of it into a bug report. It never raises — a diagnostic that
crashes on a broken install has diagnosed nothing.

## Building from source

Only needed to work on grilly2 itself.

Requirements:

- Rust (stable, MSVC target on Windows);
- the LunarG Vulkan SDK, with `VULKAN_SDK` set;
- a C++17 compiler.

```
git clone --recursive https://github.com/Grillcheese-AI/grilly2
cargo test
```

`--recursive` fetches VulkanMemoryAllocator, the one external dependency of
the Vulkan layer; `git submodule update --init --recursive` does it after
the fact. Nothing else is needed — no CMake, no second project, and **no
grilly v1 checkout**: the Vulkan device, buffer pool, pipeline cache and
command batch live in `crates/grilly-sys/vulkan/`, and every kernel is
compiled from `crates/grilly-core/shaders/` at build time and **baked into
the binary** — 173 blobs, 973 KB, so a built extension carries no path to the
machine that built it and works wherever it is installed.

Useful variables:

| variable | effect |
|---|---|
| `VMA_INCLUDE_DIR` | VulkanMemoryAllocator include directory; default is the submodule |
| `GRILLY_SHADER_DIR` | an extra SPIR-V directory, loaded after the kernels baked into the binary, so a kernel can be replaced without a rebuild |
| `GRILLY_PYTHON` | interpreter with torch and numpy, used by the op tests as the reference; default `python` |
| `GRILLY_VERBOSE` | set to 1 to print the device bring-up log |
| `GRILLY_LAUNCH_BLOCKING` | set to 1 to submit and wait after every kernel launch (as `CUDA_LAUNCH_BLOCKING`), for diagnosis |
| `ALLOW_CPU_VULKAN` | set to 1 to accept a software Vulkan device (Mesa lavapipe / llvmpipe) when no GPU is present; how CI runs the kernels |
| `VK_GPU_INDEX` | pick a Vulkan device by index, overriding the default (discrete first, then NVIDIA, then AMD) |

The GPU tests need a Vulkan 1.2 device. The op tests compare every op against
torch on CPU, so they also need torch installed for `GRILLY_PYTHON`.

CI (`.github/workflows/ci.yml`) has no GPU, so it builds both wheels and runs
both suites on lavapipe, a software Vulkan driver. That checks the numbers,
not the speed: timing, memory placement and the fence timeout still need real
hardware. Releases (`release.yml`) build a Windows and a Linux
(`manylinux_2_34`) abi3 wheel and an sdist, and publish to PyPI on a `v*` tag.

## Python

```
python -m venv .venv
.venv/Scripts/pip install maturin numpy pytest torch   # torch: reference for tests only
.venv/Scripts/maturin develop --release
.venv/Scripts/python -m pytest
```

```python
import grilly as torch          # or: python -m pytest -p grilly.torch_alias
x = torch.tensor([[1.0, -2.0]])
torch.nn.functional.linear(x, torch.ones(3, 2))
```

To run a Hugging Face checkpoint (see `docs/huggingface.md`):

```python
from grilly.huggingface import AutoModelForCausalLM, AutoTokenizer   # transformers' API
from grilly.infer.quantization import Int8WeightOnlyConfig           # torchao's API

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct",
                                             quantization_config=Int8WeightOnlyConfig())
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
ids = tokenizer.apply_chat_template([{"role": "user", "content": "Why is the sky blue?"}],
                                    add_generation_prompt=True, return_tensors="pt")
print(tokenizer.decode(model.generate(ids, max_new_tokens=128)[0]))
```

`python tools/generate.py --max-new-tokens 64` is that run: Qwen2.5-0.5B-Instruct
from the local Hugging Face cache, int8, sampled, **142–168 tokens/s** on an
RX 6750 XT with the GPU otherwise idle, 1.24 GiB of VRAM while generating, and
greedy output identical to transformers.

The spread is run-to-run, not noise in the measurement: a 64-token decode is
about 0.4 s, short enough that the card's clock state decides the number. Quote
the range, not a best run.

A decode step spends much of its token in the host, deciding what to
launch. `grilly.graphed` records a step's GPU commands once and replays
them, which removes that cost without changing the commands or the
arithmetic — measured at 1.6-2.2x on a recurrent decode step, bit-exact
against running it eagerly (`docs/capture.md`):

```python
step = grilly.graphed(model.step)      # records on the second call with a shape
for t in range(tokens):
    y, state = step(x_t, state)        # every later one replays
```

The machinery underneath takes no Hugging Face files, and works with
`grilly.huggingface` uninstalled (see `docs/inference.md`):

```python
from grilly.infer.safetensors import load_file           # safetensors.torch's API
from grilly.infer.quantization import load_quantized_, Int8WeightOnlyConfig
load_quantized_(model, "model.safetensors", Int8WeightOnlyConfig())  # quantized as it loads
model.generate(input_ids, max_new_tokens=64, do_sample=True, top_p=0.8)
```

Only float32 tensors on the default GPU exist so far, plus torch's meta
device (`with grilly.device("meta")`) for building a model without
allocating the weights a checkpoint is about to replace. Anything torch supports
that grilly does not yet raises `NotImplementedError` or fails to resolve;
nothing silently behaves differently.

## Beyond torch

The torch API is the core. Anything torch has no name for lives in its own
module, which is where domain vocabulary is allowed — `grilly.vsa` is the
first:

```python
from grilly import vsa

role, filler = vsa.random_discrete(80, 128), vsa.random_discrete(80, 128)
bound = vsa.bind(role, filler)                 # per-block circular convolution
assert vsa.similarity(vsa.unbind(bound, role), filler) == 1.0
```

Sparse block codes (IBM NVSA) and, in `grilly.vsa.packed`, binary
hypervectors 32 bits to a word. They are different algebras over different
dtypes and do not accept each other's vectors.

## Coming from grilly v1

grilly2 replaces v1 under the **same import name, a different distribution**:
`pip install grilly2`, `import grilly`. v1 holds the `grilly` name on PyPI, so
the two are separate packages that own the same top-level directory — pip does
not model that and will let the second install overwrite the first in silence.
**`pip uninstall grilly` before installing grilly2**, and if something is
already confused, `grilly-doctor` detects it and says so.

v1's import paths still work, through aliases that keep v1's signatures and
name where each thing moved to. v1's *parallel framework* — its own autograd,
`nn` and optimizers — is not reimplemented, because the torch API is the
replacement; those names raise and say what to use. `docs/v1-migration.md`
is the table.

To see which torch symbols a codebase uses and how many grilly provides:

```
python tools/torch_surface.py path/to/project --grilly
```

