Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ jobs:
"$(grep -m1 '^version' packages/rust/crates/oxbitnet-java/java/build.gradle.kts | sed 's/.*"\(.*\)"/\1/')"
check packages/rust/crates/oxbitnet-csharp/src/OxBitNet/OxBitNet.csproj \
"$(grep '<Version>' packages/rust/crates/oxbitnet-csharp/src/OxBitNet/OxBitNet.csproj | sed 's/.*<Version>\(.*\)<\/Version>/\1/' | tr -d ' ')"
check packages/rust/crates/oxbitnet-haskell/oxbitnet.cabal \
"$(grep -m1 '^version:' packages/rust/crates/oxbitnet-haskell/oxbitnet.cabal | sed 's/.*: *//')"
exit $ERRORS

# ── crates.io ──
Expand Down Expand Up @@ -388,3 +390,48 @@ jobs:
--api-key ${{ secrets.NUGET_API_KEY }} \
--source https://api.nuget.org/v3/index.json \
--skip-duplicate

# ── Hackage (Haskell) ──
publish-hackage:
needs: version-check
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: haskell-actions/setup@v2
with:
ghc-version: "9.6"
cabal-version: "3.10"

- uses: dtolnay/rust-toolchain@stable

- uses: Swatinem/rust-cache@v2
with:
workspaces: packages/rust

- name: Build native library (needed for hsc2hs)
working-directory: packages/rust
run: cargo build -p oxbitnet-ffi --release

- name: Build Haskell package
working-directory: packages/rust/crates/oxbitnet-haskell
run: |
cabal build all \
--extra-lib-dirs=../../target/release \
--extra-include-dirs=../oxbitnet-ffi

- name: Create source distribution
working-directory: packages/rust/crates/oxbitnet-haskell
run: cabal sdist

- name: Upload to Hackage
working-directory: packages/rust/crates/oxbitnet-haskell
run: |
cabal upload --publish \
dist-newstyle/sdist/oxbitnet-*.tar.gz \
--username "$HACKAGE_USERNAME" \
--password "$HACKAGE_PASSWORD"
env:
HACKAGE_USERNAME: ${{ secrets.HACKAGE_USERNAME }}
HACKAGE_PASSWORD: ${{ secrets.HACKAGE_PASSWORD }}
21 changes: 21 additions & 0 deletions packages/rust/crates/oxbitnet-haskell/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Yusuke Harada

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.
143 changes: 143 additions & 0 deletions packages/rust/crates/oxbitnet-haskell/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
# oxbitnet-haskell

Haskell bindings for [oxbitnet](https://crates.io/crates/oxbitnet) — run [BitNet b1.58](https://github.com/microsoft/BitNet) ternary LLMs with GPU acceleration (wgpu).

Part of [0xBitNet](https://github.com/m96-chan/0xBitNet).

## Build

First, build the native library:

```bash
cd packages/rust
cargo build -p oxbitnet-ffi --release
```

Produces `target/release/liboxbitnet_ffi.so` (Linux) / `.dylib` (macOS) / `oxbitnet_ffi.dll` (Windows).

Then build the Haskell package:

```bash
cd packages/rust/crates/oxbitnet-haskell
cabal build all \
--extra-lib-dirs=../../target/release \
--extra-include-dirs=../oxbitnet-ffi
```

## Quick Start

```haskell
import OxBitNet

main :: IO ()
main = withBitNet "model.gguf" defaultLoadOptions $ \model -> do
-- Raw prompt
generate model "Hello!" defaultGenerateOptions $ \token -> do
putStr token
return False -- False = continue, True = stop

-- Chat messages
chat model [userMessage "Hello!"] defaultGenerateOptions $ \token -> do
putStr token
return False
```

## API

### Loading

```haskell
-- Bracket-based (recommended)
withBitNet "model.gguf" defaultLoadOptions $ \model -> do
...

-- Manual load/free
model <- loadBitNet "model.gguf" defaultLoadOptions
-- ...use model...
freeBitNet model

-- With progress callback
let opts = defaultLoadOptions
{ onProgress = Just $ \p ->
putStrLn $ show (lpPhase p) ++ " " ++ show (lpFraction p * 100) ++ "%"
}
withBitNet "model.gguf" opts $ \model -> ...
```

### Generation

```haskell
-- Raw prompt — tokens delivered via callback
generate model "Once upon a time" defaultGenerateOptions $ \token -> do
putStr token
return False -- continue

-- With custom options
let opts = defaultGenerateOptions
{ maxTokens = 512, temperature = 0.7, topK = 40 }
generate model "Hello!" opts $ \token -> do
putStr token
return False

-- Stop early
generate model "Hello!" defaultGenerateOptions $ \token -> do
putStr token
return (token == "\n") -- stop on newline
```

### Chat

```haskell
let messages =
[ systemMessage "You are a helpful assistant."
, userMessage "What is 2+2?"
]

chat model messages defaultGenerateOptions $ \token -> do
putStr token
return False
```

### Logger

```haskell
-- Install before loading any model (can only be called once)
setLogger Info $ \level msg ->
putStrLn $ "[" ++ show level ++ "] " ++ msg
```

### Cleanup

`withBitNet` handles cleanup automatically via `bracket`. For manual management, use `loadBitNet` / `freeBitNet`. Calling `freeBitNet` multiple times is safe.

## Generation Options

| Field | Default | Description |
|-------|---------|-------------|
| `maxTokens` | 256 | Maximum tokens to generate |
| `temperature` | 1.0 | Sampling temperature |
| `topK` | 50 | Top-k sampling |
| `repeatPenalty` | 1.1 | Repetition penalty |
| `repeatLastN` | 64 | Window for repetition penalty |

## Exceptions

All errors are thrown as `OxBitNetException`:

- `LoadError String` — model failed to load
- `GenerateError String` — generation failed
- `Disposed` — attempted to use a freed model handle

## Running the Example

```bash
cd packages/rust
cargo build -p oxbitnet-ffi --release
cd crates/oxbitnet-haskell
cabal run oxbitnet-chat -- /path/to/model.gguf \
--extra-lib-dirs=../../target/release
```

## License

MIT
64 changes: 64 additions & 0 deletions packages/rust/crates/oxbitnet-haskell/examples/Chat.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
module Main where

import Control.Monad (unless)
import Data.IORef
import System.Environment (getArgs)
import System.IO (hFlush, stdout, hIsEOF, stdin, hSetBuffering, BufferMode(..))

import OxBitNet

main :: IO ()
main = do
hSetBuffering stdout NoBuffering
args <- getArgs
source <- case args of
[s] -> return s
_ -> error "Usage: oxbitnet-chat <model-path-or-url>"

let loadOpts = defaultLoadOptions
{ onProgress = Just $ \p -> do
let phaseName = case lpPhase p of
Download -> "Download"
Parse -> "Parse"
Upload -> "Upload"
pct = lpFraction p * 100.0 :: Double
putStr $ "\r[" ++ phaseName ++ "] " ++ showFFloat1 pct ++ "%"
hFlush stdout
}

putStrLn "Loading model..."
withBitNet source loadOpts $ \model -> do
putStrLn "\nModel loaded. Type a message (Ctrl-D to quit).\n"
history <- newIORef ([] :: [ChatMessage])
chatLoop model history

chatLoop :: BitNet -> IORef [ChatMessage] -> IO ()
chatLoop model history = do
putStr "> "
hFlush stdout
eof <- hIsEOF stdin
unless eof $ do
input <- getLine
unless (null input) $ do
modifyIORef' history (++ [userMessage input])
msgs <- readIORef history

responseRef <- newIORef ""
chat model msgs defaultGenerateOptions $ \token -> do
putStr token
modifyIORef' responseRef (++ token)
return False

putStrLn ""
response <- readIORef responseRef
modifyIORef' history (++ [assistantMessage response])

chatLoop model history

-- | Show a Double with 1 decimal place.
showFFloat1 :: Double -> String
showFFloat1 x =
let n = round (x * 10) :: Int
whole = n `div` 10
frac = n `mod` 10
in show whole ++ "." ++ show (abs frac)
42 changes: 42 additions & 0 deletions packages/rust/crates/oxbitnet-haskell/oxbitnet.cabal
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
cabal-version: 2.4
name: oxbitnet
version: 0.5.2
synopsis: Haskell bindings for oxbitnet — BitNet b1.58 inference with wgpu
description:
Run BitNet b1.58 ternary LLMs with GPU acceleration (wgpu).
.
This package provides Haskell bindings to the @liboxbitnet_ffi@ C library.
You must build @liboxbitnet_ffi@ separately and ensure the linker can find it.
.
See <https://github.com/m96-chan/0xBitNet> for the full project.

homepage: https://github.com/m96-chan/0xBitNet
bug-reports: https://github.com/m96-chan/0xBitNet/issues
license: MIT
license-file: LICENSE
author: Yusuke Harada
maintainer: m96.chan.mfmf@gmail.com
category: AI, FFI
extra-source-files: README.md

library
exposed-modules:
OxBitNet
Foreign.OxBitNet.Raw
build-depends:
base >= 4.14 && < 5
hs-source-dirs: src
default-language: Haskell2010
extra-libraries: oxbitnet_ffi
include-dirs: ../../oxbitnet-ffi
includes: oxbitnet.h
ghc-options: -Wall

executable oxbitnet-chat
main-is: Chat.hs
build-depends:
base >= 4.14 && < 5,
oxbitnet
hs-source-dirs: examples
default-language: Haskell2010
ghc-options: -Wall -threaded
Loading