0
Fork 0
mirror of https://github.com/zml/zml.git synced 2026-11-16 19:11:09 +00:00
Commit graph

72 commits

Author SHA1 Message Date
Steeve Morin
45ac7973cd WIP 2024-11-06 17:27:27 +01:00
Steeve Morin
30716dd802 zml: rework device assignment when compiling the modul
First, do not copy `DeviceAssignmentProto` but use `@TypeOf` to fetch it.
Then, use a named block to set it inline.
2024-11-05 20:00:50 +01:00
Corentin Godeau
acedc63bb8 zml/module: disable donation for Neuron 2024-11-05 19:28:38 +01:00
Corentin Godeau
b311070dc5 runtimes/neuron: Set required env before Python initialization 2024-11-05 19:28:38 +01:00
Steeve Morin
bef2d3f009 runtimes/neuron: bump requirements 2024-11-05 19:28:38 +01:00
Steeve Morin
1b036259f2 +neuron 2024-11-05 19:28:38 +01:00
Steeve Morin
2110847c9a +neuron 2024-11-05 19:28:38 +01:00
Steeve Morin
c13a8fe278 runtimes/neuron: wchar handling 2024-11-05 19:28:38 +01:00
Steeve Morin
54873b8476 neurontmp 2024-11-05 19:28:35 +01:00
Steeve Morin
e60ebe064f NEURON 2024-11-05 19:26:39 +01:00
Steeve Morin
38e3bd2a04 neuron 2024-11-05 19:26:39 +01:00
Steeve Morin
3efc78d273 neuron 2024-11-05 19:26:39 +01:00
Steeve Morin
27b7d31b40 neuron 2024-11-05 19:26:39 +01:00
Steeve Morin
fad7cc0876
zml: reintroduce pjrtx (#78)
In an async scenario, it is very easy to footgun yourself and block the
reactor, especially with Events.

Reintroduce pjrtx that deals with the specifics.
2024-11-05 19:25:50 +01:00
Steeve Morin
44d1b24beb
async: add threaded implementation (#77)
This implements the `async` module using a thread pool. This is now the
default.

Implementations can be swapped using the
`@zml//async:impl=[threaded,zigcoro]` flag.

Because io_uring is not enabled in the default seccomp profile, some
container implementations will block on io_uring calls. Use the threaded
implementation to work around this, for now.
2024-11-05 16:47:41 +01:00
Guillaume Wenzek
f661e1a45d
zml/aio: allow metadata to be read from index.json (#76)
For sharded safetensor files, we already have a separate json file we
need to read.
Let's allow writing metadata there, to avoid having a separate json file
with the model config.
2024-11-05 16:45:45 +01:00
Guillaume Wenzek
2febb10baa
zml.tensor: add triangular and toDiagonal (#75)
- triangular: zeroes out the upper right part of a matrix. Options
control how much is actually zeroes with offset from the diagonal.
- toDiagonal: equivalent to pytorch "diag_embed". The base case is
converting a vector into a diagonal matrix. We already have a `diag`
operator doing this, but the name was wrong cause in general `diag` does
the reverse operation of extracting the diagonal from a matrix into a
vector. Also it was using old style ZML, and was a bit too restrictive
on input shapes.
- elu: one more activation function. it's getting a bit out of hand, I've put it under zml.nn.Activation
2024-11-04 15:30:55 +01:00
Guillaume Wenzek
cb0bcf2f7b
zml.tensor: add cumulativeSum, small refactor of maxPoolND (#64)
This PR adds the "cumulative sum" operator.

This is based on what jax does, which is leveraging reduce window
operator,
where for each n in [0..N] you compute the some of elements [0..n] 
I'm not sure how this get optimized in complex programs, to be
investigated.

**BREAKING CHANGES**:
* `reduceWindow` is still pretty hard to used but I merged the
`padding_shape` and `padding_value` into one operator and made the
signature more explicit.
* this also lead me to change a bit how `maxPool1D` and `maxPool2D` take
arguments, using proper tuples instead of slices that need to be of
specific len.
* `pad` now take options using 
     * "tagged syntax":`x.pad(0, .{ .a = .{ .low = 1, .high = -1 }});` 
* or the "AOS syntax": `x.pad(0, &.{.{}, { .low = 1, .high = -1 }});`
* the "SOA syntax" is **REMOVED**: `x.pad(0, .{ .low = &.{1}, .high =
&.{-1} });`
2024-11-04 09:45:32 +01:00
Steeve Morin
09f8506763
runtimes: add intermediate abstraction layer (#74)
Add a tiny abstraction layer between ZML and PJRT.

Most notably, to implement custom logic to decide wether or not we
should/can load a PJRT plugin.

For instance, `libtpu` will block the program trying to reach the GCP
metadata server, which doesn't exist outside GCP.

This also allows for comptime detection of wether a runtime is linked
with the program, and its dependencies.
2024-11-01 18:07:33 +01:00
Steeve Morin
ee6aaea850
zml: configure runfiles env at context start (#73)
If we start bazel built binaries inside a ZML process, the environment
has to be configured properly for the sub processes to find their
runfiles properly.
Do it process wide at context start.
2024-11-01 17:44:47 +01:00
Steeve Morin
a3a5a6336c
zml,pjrt: account for runtimes that not implementing Events (#72)
Some runtimes do not implement `PJRT_Event`. For those, we must dispatch
on our own thread pool for buffer copies and wait on events only if the
runtime returns them.

If there are no events, assume all operations are synchronous.
2024-11-01 17:38:14 +01:00
Steeve Morin
ccd925309b
async: rename async_ to asyncc and add Generic slugs (#71)
`asyncc` is arguably nicer to write than `async_`, so use that.

Also, add an explicit `Generic` version that can work with `anytype`
functions (but on which type inference will be disabled).
2024-11-01 17:36:08 +01:00
Steeve Morin
be510cbb6b
bazel,runtimes/rocm: use dynamic symbol import renaming (#70)
Currently, in ROCm, we use
`__attribute__((ifunc("_zml_rocm_resolve_dlopen")))` to make sure
`dlsym(RTLD_NEXT, "dlopen")` will resolve to the real `dlopen` and not
the always failing stub.

This is a bit brittle.

Instead, leverage `patchelf`'s `rename_dynamic_symbols` feature to
import a custom `dlopen` implementation, and forward to the real one
normally.
2024-11-01 17:33:57 +01:00
Hugo Mano
62a05cc2f8
zml/tensor: use stablehlo.logistic for silu and remove logistic to implement it in sigmoid [BREAKING CHANGE] (#69)
For `silu`, `logistic` is more precise than `sigmoid` since the first
one is bound to StableHLO while the second one is a custom
implementation. Implemented `logistic` implementation in `sigmoid`
and aliased `logistic` to `sigmoid`.
2024-10-29 11:23:33 +01:00
Guillaume Wenzek
468e432fca
zml/testing: handle all float types in tests (#66)
Handle all float types. Before we would crash if the reference tensor
was in bfloat16.
2024-10-23 17:39:26 +02:00
Corentin Godeau
c61ef6bd1d
Fix LSP in Neovim (#65)
`zig_exe_path` needs to be set for the LSP to work properly
2024-10-23 14:07:48 +02:00
Farookh Zaheer Siddiqui
7f6dbbe289
[Docs] : fix typos (#60) 2024-10-22 17:38:05 +02:00
Victor Moin
db665ba706
Add missing load in dockerize_models.md (#62)
Added the missing import `zig_cc_binary` in the simple layer example,
even though it seems obvious when you read the error
2024-10-22 17:35:51 +02:00
Guillaume Wenzek
4a5c579a10
zml: concatenate tag support (#61)
* add support for `Tensor.concatenate(&.{x, y}, .d)`
* start removing some `broadcastLeft` usage
* use f32 to compute head scaling constant in transformer. We should
always compute constant with max precision.
2024-10-18 12:33:46 +02:00
Guillaume Wenzek
edc0454d6c
zml.aio.torch: more refactor (#59)
* use more complicated test cases with long integers
* add tests for protocol 0. Pickle as evolve a lot since protocol 0 was
there,
and it's unlikely we receive such pickle, I thought it was justified
since a big part of the code is related to protocol 0 anyway.
* add tests to the "zipped pickle"
* simplify structs hierarchy -> `PickleData` has been merged with
`Parser` into `torch.File`.
* rename `torch/value.zig` -> `torch/py_object.zig`
* intermediary results: []pickle.Op, []py_object.AnyPy, should not be
stored inside objects but passed around function calls.
* we should use buffered reader to parse the pickle and the zip headers
* python Dict should not be represented by a singleton seq of seq of seq
of kv, just a single seq with keys and values following each other is
enough (like in pickle protocol)
* kwargs should not be mixed with args
* added harder pytorch test with a raw tensor and a `torch.nn.Conv2d`
module
* simplified a bit lifecylcle of `BufferStore` by passing the files
during init.
2024-10-18 11:32:38 +02:00
Corentin Godeau
7a35d53ea3
Add Llama 3.1 70B Instruct model (#56)
This can be handy to test beefier models on powerful accelerators
2024-10-17 17:05:24 +02:00
Corentin Godeau
cb31e4a749
Llama weights sharding (#58)
This PR introduces sharding attributes to Llama weights to take
advantage of Tensor Parallelism
2024-10-17 17:05:10 +02:00
Corentin Godeau
ccee18ec20
Bump PJRT CUDA Plugin to v0.2.3 (#57)
This adds NCCL support which is required for proper sharding use
2024-10-17 17:04:48 +02:00
Corentin Godeau
4f27be8e37
Wait for events when calling a module (#53)
This PR includes two changes:
* Proper handling of multi-device for sharding
* Actually waiting for events to be signaled
2024-10-17 17:04:33 +02:00
Guillaume Wenzek
895492dee4
zml.aio.torch: rename zml.aio.Value -> zml.aio.Metadata (#55)
Part of ongoing improvements to the torch loader

* rename zml.aio.Value -> zml.aio.Metadata
* simplify the types zml.aio.Metadata can have
* pickle `parse` function moved to `pickle.zig`
* add dedicated test case
* fix small bug in parse where `short_binstring` was converted to
`bin_string`
* pickle `evaluate` function now returns `[]const zml.aio.torch.Value`

note: I didn't modified the core logic.
2024-10-17 16:16:05 +02:00
Guillaume Wenzek
72a1c5954b
zml/aio/torch: rename (#52)
Applying a few principles from Zig style guide:

### [Redundant names in fully qualified
namespace](https://ziglang.org/documentation/0.13.0/#Avoid-Redundant-Names-in-Fully-Qualified-Namespaces)
:

ops.PickleOp -> pickle.Op
parser.Decoder -> parser.Parser

### [Avoid generic
names](https://ziglang.org/documentation/0.13.0/#toc-Avoid-Redundancy-in-Names)
:

removed "utils.zig" and inlined the code where used.

### allow to read file top to bottom

sorted functions in `aio/torch.zig` by the order of call.
extracted some part of the code into functions `parseTensor`,
`parseStorage`
2024-10-14 15:41:52 +02:00
Guillaume Wenzek
27add022a9
zml: fix testLayer (#49)
`testLayer` was broken because it wasn't directly used by `llama.zig`.

Remove the uneeded "compile_options" argument,
update the testing logic to the new sharded output.
2024-10-14 09:53:38 +02:00
Guillaume Wenzek
9cf68e0bec
Try to read normalizer setting from the huggingface json (#47)
We had issues with the CodeLlama tokenizer.
https://huggingface.co/codellama/CodeLlama-7b-hf

Looking at the config, it's actually a "sentencepiece" tokenizer, that
uses the special "▁" token to represent spaces.

```
"normalizer": {
    "type": "Sequence",
    "normalizers": [
      {
        "type": "Prepend",
        "prepend": "▁"
      },
      {
        "type": "Replace",
        "pattern": {
          "String": " "
        },
        "content": "▁"
      }
    ]
  },
```

I've added a `Normalizer.fromHfJson` that reads this json and tries to
convert this style to our options.
This config can express more things than we can, so it's a best effort.
I've also made the magic space token configurable, requiring adding a
small buffer in Normalizer to store it.

There is a small change that can have importance, is that now in most
cases the setting "remove_extra_whitespaces" will not be set, meaning
that user input will be tokenized differently in face of double spaces.
I generally don't think this is a good practice, but it respect HF
defaults.

I've also added a `debug` boolean on the tokenizer struct that shows the
individual merges of tokens.
It helped me previously when debugging tokenizer issues.
Before you needed to explicitly uncomment some code to use it, now it's
behind a runtime boolean.

---------

Co-authored-by: Rene Schallner <rene@zml.ai>
2024-10-11 15:27:51 +02:00
Guillaume Wenzek
164a2f2c70
zml.aio.json: fix loading empty array (#50)
safetensor loader was segfaulting when loading metadata with an empty
json array.

I also rewrote some of the torch loader code to improve the readability.
Notably every slice in `ops.zig` is now const. I've also realized that
our strategy to load Pytorch tensor is not future proof see the warning
at: https://pytorch.org/docs/stable/storage.html
2024-10-11 13:26:04 +02:00
Hugo Mano
f26a022aa2
zml/sharding: user sharding constraints api and hlo integration (#46)
- Introduce sharding hints from the user code to specify how operations
should be split across user's devices mesh leveraging the HLO sharding
annotations
- Remove options arguments in `zml.module` including
`opts.add_donations_attributes`: it's for the function caching because inner function can't do donation, so we don't want to put the donation attributes there but for now we it's removed and we will do it differently next time around
2024-10-10 13:56:49 +02:00
Guillaume Wenzek
9a895ac0e6
make zml/test_runner.zig public (#48)
The end goal is to allow zml users to use our async test runner in their
project.

This approach works but is a bit hacky because it relies on the fact
that `test_runner.zig` is part of the `zml` library
otherwise `zig_test` doesn't correctly put the test_runner into the
build sandbox.

I made this dependency explicit, but it was already the case because of
the glob pattern used in zml library.

And I think `test_runner` should be `zig_library` in the first place,
and not a filegroup.
See https://github.com/zml/rules_zig/issues/2 for follow up.
2024-10-09 11:02:16 +02:00
Steeve Morin
9b3491f4bf
workspace: be a little more precise regarding the huggingface token (#45)
Indicate that it's also the standard location used by the CLI, and add
the environment variable, too.

---------

Co-authored-by: Rene Schallner <rene@renerocks.ai>
2024-10-06 14:34:38 -07:00
Jon Stevens
a050b3f9ce
make the token directory first if it doesn't already exist (#44) 2024-10-04 11:52:57 -07:00
Jean-Baptiste Dalido
e5c43e2799
runtimes/cuda: fix versions in build (#43)
We missed a variable bump for runtimes/cuda in #ea0b204, making it
impossible to build CUDA.
2024-10-04 16:04:09 +02:00
Guillaume Wenzek
76a68980c8
zml: move tests next to the tested function (#42)
note: `dynamicSlice1d()` has been completely removed because the `test
dynamicSlice` has already very similar test.
2024-10-04 09:42:21 +02:00
Guillaume Wenzek
ec9f69add7
zml: remove pjrtx (#38)
pjrtx.zig was mean to be a ZML specific wrapper over pjrt.zig.
But pjrt.zig in its current form is pretty usable without wrapper,
the extra layer of indirection is IMHO confusing because it mostly
transfer the calls directly to pjrt.zig but make some call suspending.

I moved the few helpers left in pjrtx.zig where they are used, ie 

`pjrtx.Buffer.bufferFromHostBuffer`-> in `buffer.Buffer.from`
`pjrtx.Client.compile` -> in `module.compileModuleToPjrtExecutable`
`pjrtx.Event.await` -> `zml.Platform.awaitEvent()`

This also fix a bug in `pjrtx.Event.await` which was blocking for the
event before suspending for the event.
2024-10-04 09:32:53 +02:00
Steeve Morin
0049efdd0c
runtimes/cuda: bump cuda=12.6.2 and cudnn=9.4.0 (#40) 2024-10-03 09:42:17 -04:00
Steeve Morin
ea0b204af8
runtimes/rocm: bump ROCm to 6.2.2 (#39) 2024-10-03 09:41:57 -04:00
Guillaume Wenzek
db861fd5e2
zml.tokenizer: proper byte fallback support (#37)
Some tokenizers have bytes encoded in hex like this: "<0x40>".
This break the tokenization algorithm because the input text will
contain "@" not "<0x40>",
and if the input contains "<0x40>" it needs to not be treated as a
single byte.
So we replace byte fallbacks strings, by their corresponding character.
This enables the normal tokenization algorithm to work.

This PR also implement the main byte fallback logic, that split unknow
utf8 codepoint into bytes.

---------

Co-authored-by: cryptodeal <james@zml.ai>
2024-10-01 21:15:59 +02:00
Guillaume Wenzek
2251b1d815
zml: sharding (#26)
First rough support for in-process sharding.
The goal of sharding is to allow leveraging several GPUs to collaborate
to run one big model.

Current implementation:
* added `platform.sharding()` describing how the set of devices managed
by the current process should be used.
* added a `_sharding_info` to shape.
* A tensor / shape axis can be marked as needing sharding using
`.withSharding(.{ .a })` or `.withSharding(.{ 1 })`.
* When using `populateModelWeights` tensors with sharded axes, will be
populated by sharded buffers.
* when generating the MLIR bytecode for a ZML function the **input**
arguments, will see their `_sharding_info` converted into
`mhlo.sharding` attributes
2024-10-01 21:12:25 +02:00