Metadata-Version: 2.4
Name: rasna
Version: 0.0.1
Summary: Rasna: Realtime Adaptive Sparse Neural Accelerator
Author-email: Akira Jinguji <akira@example.com>
License: Rasna Proprietary License
        
        Copyright (c) 2026 Akira Jinguji. All rights reserved.
        
        This software, including source code, object code, documentation, examples,
        models, compiled programs, and any associated materials, is proprietary.
        
        1. Grant of Permission
        
        Permission is granted only to access and use this software for personal,
        internal, non-commercial evaluation purposes, unless a separate written
        agreement with the copyright holder expressly grants additional rights.
        
        No ownership rights are transferred. All rights not expressly granted in this
        license are reserved by the copyright holder.
        
        2. Restrictions
        
        You may not, without prior written permission from the copyright holder:
        
        - use this software or any derivative, compiled artifact, service, or output
          based on this software for commercial purposes;
        - modify, adapt, translate, transform, fork, or create derivative works of this
          software;
        - copy, publish, sublicense, sell, rent, lease, distribute, transfer, host,
          make available, or otherwise redistribute this software or any part of it;
        - reverse engineer, decompile, disassemble, inspect, analyze, or otherwise
          attempt to derive source code, implementation details, algorithms, protocols,
          instruction formats, or internal designs from this software or any compiled
          artifact;
        - remove, obscure, or alter copyright notices, license notices, proprietary
          markings, or attribution notices;
        - use this software to provide services to third parties, including hosted,
          cloud, SaaS, consulting, benchmarking, integration, or outsourcing services.
        
        3. No Open Source License
        
        This license is not an open source license. No permission is granted under any
        open source license unless a separate written notice explicitly says otherwise.
        
        4. Third-Party Components
        
        Third-party components included with or used by this software may be subject to
        their own license terms. Those third-party license terms govern the applicable
        third-party components only and do not grant rights to Rasna itself.
        
        5. Termination
        
        Any permission granted by this license terminates automatically if you violate
        any term of this license. Upon termination, you must immediately stop using the
        software and delete all copies in your possession or control.
        
        6. Disclaimer
        
        This software is provided "as is", without warranty of any kind, express or
        implied, including but not limited to warranties of merchantability, fitness for
        a particular purpose, and non-infringement. The copyright holder is not liable
        for any claim, damages, or other liability arising from or related to the
        software or its use.
        
        7. Separate Agreements
        
        Commercial use, modification, redistribution, reverse engineering permissions,
        or any other rights not granted here require a separate written license
        agreement signed by the copyright holder.
        
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy<3,>=2
Requires-Dist: torch<3,>=2
Requires-Dist: torchvision<1,>=0.17
Dynamic: license-file

# Rasna Python

Rasna は PyTorch モデルを Rasna runtime で実行するための Python ライブラリです。主な入口は次の 4 つです。

- `rasna.tune()`: Rasna 向けの疎化と量子化の影響を入れて、モデルをファインチューニングできる状態にします。
- `rasna.compile()`: `eval()` 済みの PyTorch モデルと sample input から `Program` を生成します。
- `Program.save()` / `rasna.load()`: コンパイル済み program を `.rasna` ファイルとして保存、再読み込みします。
- `Runtime` / `RuntimeCSim`: 別途配布される runtime object と `Program` を組み合わせて推論を実行します。

このディレクトリ以下は PyPI package `rasna` として配布されます。bitstream や simulator shared library などの runtime object は Python package には含まれず、別途配布されます。

## License

Rasna は proprietary software です。オープンソースライセンスではありません。商用利用、改変、再配布、リバースエンジニアリングは禁止されています。詳細は同梱の `LICENSE` を確認してください。

## Installation

```sh
pip install rasna
```

Rasna は NumPy と PyTorch に依存します。CUDA 版など特定の PyTorch wheel が必要な場合は、先に環境に合った PyTorch を入れてから Rasna を入れてください。

```sh
pip install torch torchvision
pip install rasna
```

## 基本フロー

Rasna を初めて使うときの流れは次の通りです。

1. PyTorch モデルを用意する、または checkpoint から読み込む。
2. `rasna.tune()` を呼び、Rasna 向けにファインチューニングできる状態にする。
3. 通常の PyTorch training loop でファインチューニングする。
4. `model.eval()` に切り替える。
5. 代表的な batch-first sample input と一緒に `rasna.compile()` へ渡す。
6. 生成された `Program` を `.rasna` ファイルに保存する。
7. 後で `.rasna` と runtime object を読み込み、runtime で実行する。

## rasna.tune

`rasna.tune()` は supported layer を in-place に変更し、Rasna の実行条件に近い量子化効果と sparsity mask を入れた状態でファインチューニングできるようにします。

```python
import torch
import rasna

model = MyModel()
model.load_state_dict(torch.load("checkpoint.pt", map_location="cpu"))

rasna.tune(
    model,
    sp=0.8,
    ab=8,
    wb=8,
    ib=17,
    chpad=True,
    strategy="auto",
)

model.train()
for images, labels in train_loader:
    optimizer.zero_grad()
    loss = criterion(model(images), labels)
    loss.backward()
    optimizer.step()
```

主な引数は次の通りです。

- `sp`: weight pruning の sparsity ratio。既定値は `0.8` です。
- `ab`: activation quantization bit width。既定値は `8` です。
- `wb`: weight quantization bit width。既定値は `8` です。
- `ib`: tuning 中の中間値 bit width。既定値は `17` です。
- `chpad`: `Conv2d` の padding mode を circular にします。既定値は `True` です。
- `strategy`: `"auto"` は first convolution、depthwise convolution、linear layer の sparsity を避けます。`"all"` は supported `Conv2d` / `Linear` すべてに sparsity を適用します。

ファインチューニング後の PyTorch checkpoint は、通常の PyTorch モデルと同じように保存できます。

## rasna.compile

`rasna.compile()` は `eval()` 済みの PyTorch モデルと、1 つ以上の batch-first sample input を受け取り、`Program` を返します。この関数はモデルを実行する runtime object を生成しません。

```python
import torch
import rasna

model.eval()

# 4D input は batch-first です。既定では channel-last の BHWC を使います。
sample = torch.randn(16, 32, 32, 3)

program = rasna.compile(model, sample)
program.save("model.rasna")
```

PyTorch model を channel-first `BCHW` で書いている場合は、`channel_last=False` を指定します。

```python
sample = torch.randn(16, 3, 32, 32)
program = rasna.compile(model, sample, channel_last=False)
```

複数入力モデルでは、sample input を位置引数としてすべて渡します。

```python
program = rasna.compile(model, sample_left, sample_right)
```

現在 trace できる主な演算は、`Conv2d`, `Linear`, `ReLU`, `BatchNorm2d`, `MaxPool2d`, `AdaptiveAvgPool2d`, `torch.flatten`, tensor add/sub, scalar affine operation です。未対応の演算がある場合は、compile 時に FX node 名つきで報告されます。

## Program の save / load

`Program` は Rasna のコンパイル済み artifact です。入力・出力の説明と、runtime に渡す instruction stream を保持します。

```python
program.save("model.rasna")

loaded = rasna.load("model.rasna")
```

program file には `.rasna` 拡張子を使います。コンパイルに時間がかかる場合、training code と deployment code を分けたい場合、または別のマシンで runtime 実行したい場合は、`Program.save()` で保存しておくと便利です。

## Runtime

runtime 実行には、コンパイル済み `Program` と、その program に対応する runtime object が必要です。Python package には runtime object は含まれません。

- simulator runtime object は通常 `.so` shared library として配布されます。
- device runtime object は通常 `.bit` bitstream と、その実行に必要な付随ファイルとして配布されます。

`Program` から runtime を作ります。

```python
import numpy as np
import rasna

program = rasna.load("model.rasna")
runtime = program.to_runtime("/path/to/runtime-object.so")  # simulator
# runtime = program.to_runtime("/path/to/runtime-object.bit")  # device

x = np.random.randn(2, 32, 32, 3).astype(np.float32)
y = runtime(x)
```

`program.to_runtime()` は `.so` path では `RuntimeCSim` を、それ以外の runtime object path では `Runtime` を生成します。bitstream を使う device 実行では、配布された runtime object を読み込める Python 環境、たとえば PYNQ 環境が必要です。

runtime input は leading batch dimension つきでも渡せます。compile と実行を channel-first でそろえる場合は `channel_last=False` を指定します。

```python
y = runtime(x_nchw, channel_last=False)
```

既定では、runtime は compile 時に決まった fixed-point type に合わせて入出力を normalize します。すでに packed 済みの `int8` / `uint8` 値を渡す場合は `normalize=False` を使います。

```python
y_int = runtime(x_int8, normalize=False)
```

## End-to-End Example

```python
import torch
import rasna

model = MyModel()
model.load_state_dict(torch.load("checkpoint.pt", map_location="cpu"))

rasna.tune(model, sp=0.8)

model.train()
for images, labels in train_loader:
    optimizer.zero_grad()
    loss = criterion(model(images), labels)
    loss.backward()
    optimizer.step()

model.eval()
sample = torch.randn(8, 32, 32, 3)

program = rasna.compile(model, sample)
program.save("model.rasna")
```

runtime object がある環境では、保存済み program を読み込んで実行できます。

```python
import numpy as np
import rasna

program = rasna.load("model.rasna")
runtime = program.to_runtime("/path/to/rasna-runtime.so")

inputs = np.random.randn(1, 32, 32, 3).astype(np.float32)
outputs = runtime(inputs)
```

## モデル作成時の注意

- `rasna.compile()` の前に必ず `model.eval()` を呼んでください。
- `rasna.compile()` に渡す sample input には leading batch dimension が必要です。
- sample input の値は fixed-point type や buffer layout の決定に使われるため、実運用に近い代表値を使ってください。
- 未対応の PyTorch operation は compiled model の外に出すか、supported module / tensor operation に書き換えてください。
- model、input shape、target configuration、runtime object が変わった場合は再コンパイルしてください。
