kiwi-array 0.5.0__py3-none-macosx_14_0_arm64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kiwi_array/__init__.py +39 -0
- kiwi_array/_native/kiwi +0 -0
- kiwi_array/_native/libkiwi_bridge.dylib +0 -0
- kiwi_array/bridge.py +294 -0
- kiwi_array/cli.py +25 -0
- kiwi_array/notebook.py +140 -0
- kiwi_array-0.5.0.dist-info/METADATA +60 -0
- kiwi_array-0.5.0.dist-info/RECORD +10 -0
- kiwi_array-0.5.0.dist-info/WHEEL +4 -0
- kiwi_array-0.5.0.dist-info/entry_points.txt +2 -0
kiwi_array/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .bridge import (
|
|
4
|
+
STATUS_NAMES,
|
|
5
|
+
KiwiBridgeError,
|
|
6
|
+
KiwiEvalResult,
|
|
7
|
+
KiwiSession,
|
|
8
|
+
find_cli_path,
|
|
9
|
+
find_library_path,
|
|
10
|
+
platform_library_name,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__version__ = "0.5.0"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_ipython_extension(ipython) -> None:
|
|
17
|
+
from .notebook import load_ipython_extension as _load
|
|
18
|
+
|
|
19
|
+
_load(ipython)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def unload_ipython_extension(ipython) -> None:
|
|
23
|
+
from .notebook import unload_ipython_extension as _unload
|
|
24
|
+
|
|
25
|
+
_unload(ipython)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"__version__",
|
|
30
|
+
"STATUS_NAMES",
|
|
31
|
+
"KiwiBridgeError",
|
|
32
|
+
"KiwiEvalResult",
|
|
33
|
+
"KiwiSession",
|
|
34
|
+
"find_cli_path",
|
|
35
|
+
"find_library_path",
|
|
36
|
+
"load_ipython_extension",
|
|
37
|
+
"platform_library_name",
|
|
38
|
+
"unload_ipython_extension",
|
|
39
|
+
]
|
kiwi_array/_native/kiwi
ADDED
|
Binary file
|
|
Binary file
|
kiwi_array/bridge.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ctypes
|
|
4
|
+
import os
|
|
5
|
+
import platform
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
DEVICE_VALUES = {"auto": 0, "cpu": 1, "gpu": 2}
|
|
11
|
+
|
|
12
|
+
STATUS_NAMES = {
|
|
13
|
+
0: "ok",
|
|
14
|
+
1: "parse",
|
|
15
|
+
2: "type",
|
|
16
|
+
3: "name",
|
|
17
|
+
4: "domain",
|
|
18
|
+
5: "rank",
|
|
19
|
+
6: "nyi",
|
|
20
|
+
7: "length",
|
|
21
|
+
8: "index",
|
|
22
|
+
9: "device",
|
|
23
|
+
10: "error",
|
|
24
|
+
11: "oom",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
DTYPE_CODES = {
|
|
28
|
+
"bool": 0,
|
|
29
|
+
"uint8": 1,
|
|
30
|
+
"int32": 2,
|
|
31
|
+
"int64": 3,
|
|
32
|
+
"float32": 4,
|
|
33
|
+
"float64": 5,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
CODE_TO_CTYPE = {
|
|
37
|
+
1: ctypes.c_uint8,
|
|
38
|
+
2: ctypes.c_int32,
|
|
39
|
+
3: ctypes.c_int64,
|
|
40
|
+
4: ctypes.c_float,
|
|
41
|
+
5: ctypes.c_double,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _CKiwiResult(ctypes.Structure):
|
|
46
|
+
_fields_ = [
|
|
47
|
+
("status", ctypes.c_int),
|
|
48
|
+
("echoed", ctypes.c_bool),
|
|
49
|
+
("text", ctypes.c_void_p),
|
|
50
|
+
("text_len", ctypes.c_size_t),
|
|
51
|
+
("display_mime", ctypes.c_void_p),
|
|
52
|
+
("display_mime_len", ctypes.c_size_t),
|
|
53
|
+
("display_data", ctypes.c_void_p),
|
|
54
|
+
("display_data_len", ctypes.c_size_t),
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _CKiwiArrayView(ctypes.Structure):
|
|
59
|
+
_fields_ = [
|
|
60
|
+
("dtype", ctypes.c_int),
|
|
61
|
+
("data", ctypes.c_void_p),
|
|
62
|
+
("len", ctypes.c_size_t),
|
|
63
|
+
("ndim", ctypes.c_size_t),
|
|
64
|
+
("dims", ctypes.c_int64 * 8),
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _CKiwiTok(ctypes.Structure):
|
|
69
|
+
_fields_ = [
|
|
70
|
+
("kind", ctypes.c_uint32),
|
|
71
|
+
("start", ctypes.c_uint32),
|
|
72
|
+
("end", ctypes.c_uint32),
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class KiwiEvalResult:
|
|
78
|
+
status: str
|
|
79
|
+
echoed: bool
|
|
80
|
+
text: Optional[str]
|
|
81
|
+
display_mime: Optional[str] = None
|
|
82
|
+
display_data: Optional[str] = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class KiwiBridgeError(RuntimeError):
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def platform_library_name(stem: str = "kiwi_bridge") -> str:
|
|
90
|
+
sys_name = platform.system()
|
|
91
|
+
if sys_name == "Darwin":
|
|
92
|
+
return f"lib{stem}.dylib"
|
|
93
|
+
if sys_name == "Windows":
|
|
94
|
+
return f"{stem}.dll"
|
|
95
|
+
return f"lib{stem}.so"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def platform_cli_name(stem: str = "kiwi") -> str:
|
|
99
|
+
if platform.system() == "Windows":
|
|
100
|
+
return f"{stem}.exe"
|
|
101
|
+
return stem
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def find_library_path() -> Path:
|
|
105
|
+
env_path = os.environ.get("KIWI_V2_BRIDGE_LIB") or os.environ.get("KIWI_BRIDGE_LIB")
|
|
106
|
+
if env_path:
|
|
107
|
+
p = Path(env_path).expanduser().resolve()
|
|
108
|
+
if p.is_file():
|
|
109
|
+
return p
|
|
110
|
+
raise KiwiBridgeError(f"KIWI_BRIDGE_LIB points to missing file: {p}")
|
|
111
|
+
|
|
112
|
+
fname = platform_library_name("kiwi_bridge")
|
|
113
|
+
pkg_native = Path(__file__).resolve().parent / "_native" / fname
|
|
114
|
+
if pkg_native.is_file():
|
|
115
|
+
return pkg_native
|
|
116
|
+
|
|
117
|
+
for parent in Path(__file__).resolve().parents:
|
|
118
|
+
cand = parent / "zig-out" / "lib" / fname
|
|
119
|
+
if cand.is_file():
|
|
120
|
+
return cand
|
|
121
|
+
|
|
122
|
+
raise KiwiBridgeError(f"Could not find {fname} in {pkg_native.parent} or zig-out/lib")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def find_cli_path() -> Path:
|
|
126
|
+
env_path = os.environ.get("KIWI_CLI_BIN")
|
|
127
|
+
if env_path:
|
|
128
|
+
p = Path(env_path).expanduser().resolve()
|
|
129
|
+
if p.is_file():
|
|
130
|
+
return p
|
|
131
|
+
raise FileNotFoundError(f"KIWI_CLI_BIN points to missing file: {p}")
|
|
132
|
+
|
|
133
|
+
fname = platform_cli_name("kiwi")
|
|
134
|
+
pkg_native = Path(__file__).resolve().parent / "_native" / fname
|
|
135
|
+
if pkg_native.is_file():
|
|
136
|
+
return pkg_native
|
|
137
|
+
|
|
138
|
+
for parent in Path(__file__).resolve().parents:
|
|
139
|
+
cand = parent / "zig-out" / "bin" / fname
|
|
140
|
+
if cand.is_file():
|
|
141
|
+
return cand
|
|
142
|
+
|
|
143
|
+
raise FileNotFoundError(f"Could not find {fname} in {pkg_native.parent} or zig-out/bin")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _load_cdll(path: Path) -> ctypes.CDLL:
|
|
147
|
+
lib = ctypes.CDLL(str(path))
|
|
148
|
+
lib.kiwi_create.argtypes = [ctypes.c_int]
|
|
149
|
+
lib.kiwi_create.restype = ctypes.c_void_p
|
|
150
|
+
lib.kiwi_destroy.argtypes = [ctypes.c_void_p]
|
|
151
|
+
lib.kiwi_destroy.restype = None
|
|
152
|
+
lib.kiwi_eval.argtypes = [
|
|
153
|
+
ctypes.c_void_p,
|
|
154
|
+
ctypes.c_char_p,
|
|
155
|
+
ctypes.c_size_t,
|
|
156
|
+
ctypes.POINTER(_CKiwiResult),
|
|
157
|
+
]
|
|
158
|
+
lib.kiwi_eval.restype = ctypes.c_int
|
|
159
|
+
lib.kiwi_set_array.argtypes = [
|
|
160
|
+
ctypes.c_void_p,
|
|
161
|
+
ctypes.c_char_p,
|
|
162
|
+
ctypes.c_size_t,
|
|
163
|
+
ctypes.c_int,
|
|
164
|
+
ctypes.c_void_p,
|
|
165
|
+
ctypes.POINTER(ctypes.c_int64),
|
|
166
|
+
ctypes.c_size_t,
|
|
167
|
+
]
|
|
168
|
+
lib.kiwi_set_array.restype = ctypes.c_int
|
|
169
|
+
lib.kiwi_get_array.argtypes = [
|
|
170
|
+
ctypes.c_void_p,
|
|
171
|
+
ctypes.c_char_p,
|
|
172
|
+
ctypes.c_size_t,
|
|
173
|
+
ctypes.POINTER(_CKiwiArrayView),
|
|
174
|
+
]
|
|
175
|
+
lib.kiwi_get_array.restype = ctypes.c_int
|
|
176
|
+
lib.kiwi_status_name.argtypes = [ctypes.c_int]
|
|
177
|
+
lib.kiwi_status_name.restype = ctypes.c_char_p
|
|
178
|
+
lib.kiwi_runtime_info.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_size_t)]
|
|
179
|
+
lib.kiwi_runtime_info.restype = ctypes.c_char_p
|
|
180
|
+
lib.kiwi_tokenize.argtypes = [
|
|
181
|
+
ctypes.c_char_p,
|
|
182
|
+
ctypes.c_size_t,
|
|
183
|
+
ctypes.POINTER(_CKiwiTok),
|
|
184
|
+
ctypes.c_size_t,
|
|
185
|
+
]
|
|
186
|
+
lib.kiwi_tokenize.restype = ctypes.c_size_t
|
|
187
|
+
return lib
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class KiwiSession:
|
|
191
|
+
"""In-process Kiwi v2 session over the unified `kiwi.h` C ABI (zero per-call FFI frees)."""
|
|
192
|
+
|
|
193
|
+
def __init__(self, device: str = "auto", library_path: Optional[Path | str] = None) -> None:
|
|
194
|
+
if device not in DEVICE_VALUES:
|
|
195
|
+
raise ValueError(f"Unknown device {device!r}; expected one of {tuple(DEVICE_VALUES)}")
|
|
196
|
+
self.device = device
|
|
197
|
+
self.library_path = Path(library_path) if library_path else find_library_path()
|
|
198
|
+
self._lib = _load_cdll(self.library_path)
|
|
199
|
+
handle = self._lib.kiwi_create(DEVICE_VALUES[device])
|
|
200
|
+
if not handle:
|
|
201
|
+
raise KiwiBridgeError("kiwi_create returned NULL")
|
|
202
|
+
self._handle: Optional[int] = handle
|
|
203
|
+
|
|
204
|
+
def close(self) -> None:
|
|
205
|
+
if self._handle:
|
|
206
|
+
self._lib.kiwi_destroy(self._handle)
|
|
207
|
+
self._handle = None
|
|
208
|
+
|
|
209
|
+
def __enter__(self) -> "KiwiSession":
|
|
210
|
+
return self
|
|
211
|
+
|
|
212
|
+
def __exit__(self, *_: object) -> None:
|
|
213
|
+
self.close()
|
|
214
|
+
|
|
215
|
+
def __del__(self) -> None:
|
|
216
|
+
try:
|
|
217
|
+
self.close()
|
|
218
|
+
except Exception:
|
|
219
|
+
pass
|
|
220
|
+
|
|
221
|
+
def runtime_info(self) -> str:
|
|
222
|
+
if not self._handle:
|
|
223
|
+
raise KiwiBridgeError("Session is closed")
|
|
224
|
+
length = ctypes.c_size_t(0)
|
|
225
|
+
raw = self._lib.kiwi_runtime_info(self._handle, ctypes.byref(length))
|
|
226
|
+
return raw.decode("utf-8", errors="replace") if raw else "kiwi-zig-v2"
|
|
227
|
+
|
|
228
|
+
def eval(self, source: str) -> KiwiEvalResult:
|
|
229
|
+
if not self._handle:
|
|
230
|
+
raise KiwiBridgeError("Session is closed")
|
|
231
|
+
encoded = source.encode("utf-8")
|
|
232
|
+
res = _CKiwiResult()
|
|
233
|
+
self._lib.kiwi_eval(self._handle, encoded, len(encoded), ctypes.byref(res))
|
|
234
|
+
status = STATUS_NAMES.get(res.status, f"status_{res.status}")
|
|
235
|
+
text = (
|
|
236
|
+
ctypes.string_at(res.text, res.text_len).decode("utf-8", errors="replace")
|
|
237
|
+
if res.text
|
|
238
|
+
else None
|
|
239
|
+
)
|
|
240
|
+
mime = (
|
|
241
|
+
ctypes.string_at(res.display_mime, res.display_mime_len).decode("utf-8", errors="replace")
|
|
242
|
+
if res.display_mime
|
|
243
|
+
else None
|
|
244
|
+
)
|
|
245
|
+
data = (
|
|
246
|
+
ctypes.string_at(res.display_data, res.display_data_len).decode("utf-8", errors="replace")
|
|
247
|
+
if res.display_data
|
|
248
|
+
else None
|
|
249
|
+
)
|
|
250
|
+
return KiwiEvalResult(
|
|
251
|
+
status=status,
|
|
252
|
+
echoed=bool(res.echoed),
|
|
253
|
+
text=text,
|
|
254
|
+
display_mime=mime,
|
|
255
|
+
display_data=data,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
def set_global_array(self, name: str, arr: Any) -> None:
|
|
259
|
+
"""Bind a NumPy ndarray (`bool`, `uint8`, `int32`, `int64`, `float32`, `float64`) into the session."""
|
|
260
|
+
if not self._handle:
|
|
261
|
+
raise KiwiBridgeError("Session is closed")
|
|
262
|
+
import numpy as np
|
|
263
|
+
|
|
264
|
+
a = np.ascontiguousarray(arr)
|
|
265
|
+
dtype_code = DTYPE_CODES.get(a.dtype.name)
|
|
266
|
+
if dtype_code is None:
|
|
267
|
+
raise TypeError(f"Unsupported dtype {a.dtype}; expected one of {tuple(DTYPE_CODES)}")
|
|
268
|
+
name_b = name.encode("utf-8")
|
|
269
|
+
dims = (ctypes.c_int64 * a.ndim)(*[int(d) for d in a.shape])
|
|
270
|
+
rc = self._lib.kiwi_set_array(
|
|
271
|
+
self._handle, name_b, len(name_b), dtype_code, ctypes.c_void_p(a.ctypes.data), dims, a.ndim
|
|
272
|
+
)
|
|
273
|
+
if rc != 0:
|
|
274
|
+
raise KiwiBridgeError(f"set_global_array({name!r}) failed: {STATUS_NAMES.get(rc, rc)}")
|
|
275
|
+
|
|
276
|
+
def get_global_array(self, name: str) -> Any:
|
|
277
|
+
"""Read a dense numeric/byte global back as a NumPy ndarray (copying out of the borrowed view)."""
|
|
278
|
+
if not self._handle:
|
|
279
|
+
raise KiwiBridgeError("Session is closed")
|
|
280
|
+
import numpy as np
|
|
281
|
+
|
|
282
|
+
name_b = name.encode("utf-8")
|
|
283
|
+
view = _CKiwiArrayView()
|
|
284
|
+
rc = self._lib.kiwi_get_array(self._handle, name_b, len(name_b), ctypes.byref(view))
|
|
285
|
+
if rc != 0:
|
|
286
|
+
raise KiwiBridgeError(f"get_global_array({name!r}) failed: {STATUS_NAMES.get(rc, rc)}")
|
|
287
|
+
ctype = CODE_TO_CTYPE.get(view.dtype)
|
|
288
|
+
if ctype is None:
|
|
289
|
+
raise KiwiBridgeError(f"Unsupported array view dtype code {view.dtype}")
|
|
290
|
+
shape = tuple(int(view.dims[i]) for i in range(view.ndim))
|
|
291
|
+
if view.len == 0:
|
|
292
|
+
return np.empty(shape, dtype=np.dtype(ctype))
|
|
293
|
+
buf = (ctype * view.len).from_address(view.data)
|
|
294
|
+
return np.ctypeslib.as_array(buf).reshape(shape).copy()
|
kiwi_array/cli.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .bridge import find_cli_path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main() -> int:
|
|
11
|
+
try:
|
|
12
|
+
cli = find_cli_path()
|
|
13
|
+
except FileNotFoundError as exc:
|
|
14
|
+
print(exc, file=sys.stderr)
|
|
15
|
+
return 1
|
|
16
|
+
|
|
17
|
+
argv = [str(cli), *sys.argv[1:]]
|
|
18
|
+
if hasattr(os, "execv"):
|
|
19
|
+
os.execv(str(cli), argv)
|
|
20
|
+
completed = subprocess.run(argv)
|
|
21
|
+
return int(completed.returncode)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
raise SystemExit(main())
|
kiwi_array/notebook.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import platform
|
|
6
|
+
import shlex
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import uuid
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from .bridge import KiwiSession, find_library_path
|
|
13
|
+
|
|
14
|
+
_SESSION: Optional[KiwiSession] = None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _get_session(device: str = "auto") -> KiwiSession:
|
|
18
|
+
global _SESSION
|
|
19
|
+
if _SESSION is None or _SESSION.device != device:
|
|
20
|
+
if _SESSION is not None:
|
|
21
|
+
_SESSION.close()
|
|
22
|
+
_SESSION = KiwiSession(device=device)
|
|
23
|
+
return _SESSION
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def vegalite_embed_options() -> dict[str, object]:
|
|
27
|
+
options: dict[str, object] = {"actions": False, "renderer": "canvas"}
|
|
28
|
+
theme = os.environ.get("KIWI_VEGALITE_THEME", "").strip()
|
|
29
|
+
if theme and theme.lower() not in {"default", "none"}:
|
|
30
|
+
options["theme"] = theme
|
|
31
|
+
return options
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def vegalite_html(spec: object) -> str:
|
|
35
|
+
elem_id = f"kiwi-vl-{uuid.uuid4().hex}"
|
|
36
|
+
spec_json = json.dumps(spec, separators=(",", ":"))
|
|
37
|
+
options_json = json.dumps(vegalite_embed_options(), separators=(",", ":"))
|
|
38
|
+
return (
|
|
39
|
+
f'<div id="{elem_id}"></div>'
|
|
40
|
+
'<script src="https://cdn.jsdelivr.net/npm/vega@6"></script>'
|
|
41
|
+
'<script src="https://cdn.jsdelivr.net/npm/vega-lite@6"></script>'
|
|
42
|
+
'<script src="https://cdn.jsdelivr.net/npm/vega-embed@7"></script>'
|
|
43
|
+
f'<script>(function(){{if(window.vegaEmbed)window.vegaEmbed("#{elem_id}",{spec_json},{options_json});}})();</script>'
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _parse_device_flag(line: str, is_cell: bool) -> tuple[str, str]:
|
|
48
|
+
if not is_cell:
|
|
49
|
+
return "auto", line
|
|
50
|
+
tokens = shlex.split(line) if line.strip() else []
|
|
51
|
+
device = "auto"
|
|
52
|
+
if "--gpu" in tokens:
|
|
53
|
+
device = "gpu"
|
|
54
|
+
elif "--cpu" in tokens:
|
|
55
|
+
device = "cpu"
|
|
56
|
+
return device, ""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _run_code(code: str, device: str = "auto") -> None:
|
|
60
|
+
from IPython.display import display
|
|
61
|
+
|
|
62
|
+
sess = _get_session(device)
|
|
63
|
+
for line_no, raw in enumerate(code.splitlines(), start=1):
|
|
64
|
+
line = raw.rstrip("\r")
|
|
65
|
+
trimmed = line.strip(" \t")
|
|
66
|
+
if not trimmed or trimmed.startswith("/"):
|
|
67
|
+
continue
|
|
68
|
+
res = sess.eval(line)
|
|
69
|
+
if res.status != "ok":
|
|
70
|
+
raise RuntimeError(f"kiwi line {line_no}: !{res.status}")
|
|
71
|
+
if res.echoed and res.text is not None:
|
|
72
|
+
if res.display_mime and res.display_data and "vegalite" in res.display_mime:
|
|
73
|
+
try:
|
|
74
|
+
spec = json.loads(res.display_data)
|
|
75
|
+
display(
|
|
76
|
+
{"text/plain": res.text, res.display_mime: spec, "text/html": vegalite_html(spec)},
|
|
77
|
+
raw=True,
|
|
78
|
+
)
|
|
79
|
+
continue
|
|
80
|
+
except json.JSONDecodeError:
|
|
81
|
+
pass
|
|
82
|
+
print(res.text)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def load_ipython_extension(ipython) -> None:
|
|
86
|
+
from IPython.core.magic import Magics, line_cell_magic, line_magic, magics_class
|
|
87
|
+
|
|
88
|
+
@magics_class
|
|
89
|
+
class KiwiMagics(Magics):
|
|
90
|
+
@line_cell_magic("k")
|
|
91
|
+
def k(self, line: str, cell: Optional[str] = None) -> None:
|
|
92
|
+
device, _ = _parse_device_flag(line, cell is not None)
|
|
93
|
+
_run_code(cell if cell is not None else line, device=device)
|
|
94
|
+
|
|
95
|
+
@line_cell_magic("kiwi")
|
|
96
|
+
def kiwi(self, line: str, cell: Optional[str] = None) -> None:
|
|
97
|
+
device, _ = _parse_device_flag(line, cell is not None)
|
|
98
|
+
_run_code(cell if cell is not None else line, device=device)
|
|
99
|
+
|
|
100
|
+
@line_magic("kinfo")
|
|
101
|
+
def kinfo(self, line: str = "") -> None:
|
|
102
|
+
device = "gpu" if "--gpu" in line else ("cpu" if "--cpu" in line else "auto")
|
|
103
|
+
sess = _get_session(device)
|
|
104
|
+
print(f"kiwi : {sess.runtime_info()}")
|
|
105
|
+
print(f"library : {find_library_path()}")
|
|
106
|
+
print(f"python : {sys.version.split()[0]} ({platform.platform()})")
|
|
107
|
+
if platform.system() == "Linux":
|
|
108
|
+
try:
|
|
109
|
+
out = subprocess.check_output(
|
|
110
|
+
["nvidia-smi", "--query-gpu=name,driver_version,memory.total", "--format=csv,noheader"],
|
|
111
|
+
text=True,
|
|
112
|
+
timeout=3,
|
|
113
|
+
).strip()
|
|
114
|
+
print(f"nvidia-smi: {out}")
|
|
115
|
+
except Exception:
|
|
116
|
+
print("nvidia-smi: not available")
|
|
117
|
+
|
|
118
|
+
@line_magic("ksmoke")
|
|
119
|
+
def ksmoke(self, line: str = "") -> None:
|
|
120
|
+
device = "gpu" if "--gpu" in line else ("cpu" if "--cpu" in line else "auto")
|
|
121
|
+
sess = _get_session(device)
|
|
122
|
+
checks = [
|
|
123
|
+
("sum", "+/!100", "4950"),
|
|
124
|
+
("matmul_f32", "a:64 64#1.0e; +/+/(+/*)\\:[a;a]", "262144.0"),
|
|
125
|
+
("groupby", "k:100#!4; v:100#1; #(+/'v@=k)", "4"),
|
|
126
|
+
("fromcsv", '+/fromcsv["k,v\\na,10\\nb,20\\n"][`v]', "30"),
|
|
127
|
+
]
|
|
128
|
+
for name, expr, want in checks:
|
|
129
|
+
res = sess.eval(expr)
|
|
130
|
+
ok = res.status == "ok" and res.text == want
|
|
131
|
+
print(f"[{'PASS' if ok else 'FAIL'}] {name}: got={res.text!r} want={want!r} ({res.status})")
|
|
132
|
+
|
|
133
|
+
ipython.register_magics(KiwiMagics)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def unload_ipython_extension(ipython) -> None:
|
|
137
|
+
global _SESSION
|
|
138
|
+
if _SESSION is not None:
|
|
139
|
+
_SESSION.close()
|
|
140
|
+
_SESSION = None
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: kiwi-array
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Compact all-Zig K-like array language runtime, CLI, and IPython magics (SIMD, Metal, CUDA)
|
|
5
|
+
Home-page: https://kiwilang.com
|
|
6
|
+
Project-URL: Homepage, https://kiwilang.com
|
|
7
|
+
Project-URL: Repository, https://github.com/kiwi-array-lang/kiwi
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Provides-Extra: notebook
|
|
10
|
+
Requires-Dist: ipython>=8; extra == "notebook"
|
|
11
|
+
Provides-Extra: jupyter
|
|
12
|
+
Requires-Dist: kiwi-array-jupyter>=0.5.0; extra == "jupyter"
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# kiwi-array
|
|
16
|
+
|
|
17
|
+
Self-contained Python runtime, CLI, and IPython magics for **Kiwi** (`kiwi-zig-v2`) — a compact K-like array language with native SIMD, Accelerate/Metal (macOS), and dynamic CUDA/cuBLAS (Linux).
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install kiwi-array
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Each platform wheel bundles the native `libkiwi_bridge` shared library and `kiwi` CLI binary (~600 KB total; no separate backend packages required).
|
|
26
|
+
|
|
27
|
+
## Python API
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import numpy as np
|
|
31
|
+
from kiwi_array import KiwiSession
|
|
32
|
+
|
|
33
|
+
with KiwiSession() as k:
|
|
34
|
+
print(k.eval("+/1 2 3 * 10").text) # 60
|
|
35
|
+
k.set_global_array("x", np.arange(1000, dtype=np.float64))
|
|
36
|
+
print(k.eval("(+/x)%#x").text) # 499.5
|
|
37
|
+
out = k.get_global_array("x")
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## IPython / Colab / Kaggle Magics
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
%load_ext kiwi_array
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
%%k
|
|
48
|
+
x:10+2*!6
|
|
49
|
+
(+/x)%#x
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`%%kiwi` is an alias for `%%k`. Use `%kinfo` and `%ksmoke` (with optional `--gpu` or `--cpu`) for runtime diagnostics. Vega-Lite specs emitted with `` `j@... `` render inline automatically (set `KIWI_VEGALITE_THEME=dark` for dark mode).
|
|
53
|
+
|
|
54
|
+
## CLI & Jupyter Kernel
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
kiwi -e "+/!100"
|
|
58
|
+
pip install kiwi-array-jupyter
|
|
59
|
+
kiwi-array-jupyter-install --user
|
|
60
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
kiwi_array/__init__.py,sha256=alC0of05e9cFCvKxrpYAuluPzj4aHPMN_w_kAWr2oHM,742
|
|
2
|
+
kiwi_array/bridge.py,sha256=eh-pER8nLxekzzOQJov8rL9NT8TVFjqYy_Glw1ab5rs,9225
|
|
3
|
+
kiwi_array/cli.py,sha256=tixiIJAZ6Ze8Cb-6eItr7UH7sO6DCOwlJrHJzABdrEU,492
|
|
4
|
+
kiwi_array/notebook.py,sha256=dalKObC2cWzmop3LDq0o0mVNLzS_jqMsnHrwa14Pppk,5235
|
|
5
|
+
kiwi_array/_native/libkiwi_bridge.dylib,sha256=cD7NyZjY0kCe_YQbgSTrAB0jsuXaI0yxUKiCoqY44_k,675784
|
|
6
|
+
kiwi_array/_native/kiwi,sha256=WiaIuem9qMJtW-Hki-wBY3sFiQjrmY6BT0sTBkULDCQ,799256
|
|
7
|
+
kiwi_array-0.5.0.dist-info/METADATA,sha256=hGr3pCseZuVrfbX3kOtWUCZypS8Or74rXYo2u5VdjZw,1692
|
|
8
|
+
kiwi_array-0.5.0.dist-info/WHEEL,sha256=VBICvOS2ya04Zjp0hbINgmht1fFFOfTOKWdYThlL3qA,109
|
|
9
|
+
kiwi_array-0.5.0.dist-info/entry_points.txt,sha256=rHIbSUqGhESM76fFGiKgf6InC-bDRNnJdJQe8uAEBAo,45
|
|
10
|
+
kiwi_array-0.5.0.dist-info/RECORD,,
|