rshogi-core 0.2.0

A high-performance shogi engine core library with NNUE evaluation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// NOTE: 公式表記(HalfKA)をenum名に保持するため、非CamelCaseを許可する。
#![allow(non_camel_case_types)]

//! HalfKA アーキテクチャ階層
//!
//! L1 サイズごとにモジュールを分割し、L2/L3/活性化の組み合わせを enum で表現。
//!
//! # 構造
//!
//! ```text
//! HalfKANetwork
//! ├── L256(HalfKA_L256)
//! │   ├── CReLU_32_32
//! │   ├── SCReLU_32_32
//! │   └── Pairwise_32_32
//! ├── L512(HalfKA_L512)
//! │   ├── CReLU_8_96
//! │   ├── SCReLU_8_96
//! │   └── Pairwise_8_96
//! └── L1024(HalfKA_L1024)
//!     ├── CReLU_8_96
//!     ├── SCReLU_8_96
//!     ├── Pairwise_8_96
//!     ├── CReLU_8_32
//!     └── SCReLU_8_32
//! ```

mod l1024;
mod l256;
mod l512;
mod l768;

pub use l256::HalfKA_L256;
pub use l512::HalfKA_L512;
pub use l768::HalfKA_L768;
pub use l1024::HalfKA_L1024;

use crate::nnue::accumulator::DirtyPiece;
use crate::nnue::network_halfka::AccumulatorStackHalfKA;
use crate::nnue::spec::{Activation, ArchitectureSpec};
use crate::position::Position;
use crate::types::Value;

/// HalfKA 特徴量セットのネットワーク(第2階層)
///
/// L1 サイズごとにバリアントを持つ。
/// L2/L3/活性化の追加で変更不要(L1 enum 内に閉じる)。
pub enum HalfKANetwork {
    L256(HalfKA_L256),
    L512(HalfKA_L512),
    L768(HalfKA_L768),
    L1024(HalfKA_L1024),
}

impl HalfKANetwork {
    /// 評価値を計算
    #[inline(always)]
    pub fn evaluate(&self, pos: &Position, stack: &HalfKAStack) -> Value {
        match (self, stack) {
            (Self::L256(net), HalfKAStack::L256(st)) => net.evaluate(pos, st),
            (Self::L512(net), HalfKAStack::L512(st)) => net.evaluate(pos, st),
            (Self::L768(net), HalfKAStack::L768(st)) => net.evaluate(pos, st),
            (Self::L1024(net), HalfKAStack::L1024(st)) => net.evaluate(pos, st),
            _ => unreachable!("L1 mismatch: network={}, stack={}", self.l1_size(), stack.l1_size()),
        }
    }

    /// Accumulator をフル再計算
    #[inline(always)]
    pub fn refresh_accumulator(&self, pos: &Position, stack: &mut HalfKAStack) {
        match (self, stack) {
            (Self::L256(net), HalfKAStack::L256(st)) => net.refresh_accumulator(pos, st),
            (Self::L512(net), HalfKAStack::L512(st)) => net.refresh_accumulator(pos, st),
            (Self::L768(net), HalfKAStack::L768(st)) => net.refresh_accumulator(pos, st),
            (Self::L1024(net), HalfKAStack::L1024(st)) => net.refresh_accumulator(pos, st),
            _ => unreachable!("L1 mismatch"),
        }
    }

    /// 差分更新(dirty piece ベース)
    #[inline(always)]
    pub fn update_accumulator(
        &self,
        pos: &Position,
        dirty: &DirtyPiece,
        stack: &mut HalfKAStack,
        source_idx: usize,
    ) {
        match (self, stack) {
            (Self::L256(net), HalfKAStack::L256(st)) => {
                net.update_accumulator(pos, dirty, st, source_idx)
            }
            (Self::L512(net), HalfKAStack::L512(st)) => {
                net.update_accumulator(pos, dirty, st, source_idx)
            }
            (Self::L768(net), HalfKAStack::L768(st)) => {
                net.update_accumulator(pos, dirty, st, source_idx)
            }
            (Self::L1024(net), HalfKAStack::L1024(st)) => {
                net.update_accumulator(pos, dirty, st, source_idx)
            }
            _ => unreachable!("L1 mismatch"),
        }
    }

    /// 前方差分更新を試みる(成功したら true)
    #[inline(always)]
    pub fn forward_update_incremental(
        &self,
        pos: &Position,
        stack: &mut HalfKAStack,
        source_idx: usize,
    ) -> bool {
        match (self, stack) {
            (Self::L256(net), HalfKAStack::L256(st)) => {
                net.forward_update_incremental(pos, st, source_idx)
            }
            (Self::L512(net), HalfKAStack::L512(st)) => {
                net.forward_update_incremental(pos, st, source_idx)
            }
            (Self::L768(net), HalfKAStack::L768(st)) => {
                net.forward_update_incremental(pos, st, source_idx)
            }
            (Self::L1024(net), HalfKAStack::L1024(st)) => {
                net.forward_update_incremental(pos, st, source_idx)
            }
            _ => unreachable!("L1 mismatch"),
        }
    }

    /// ファイルから読み込み
    ///
    /// L1/L2/L3/活性化に基づいて適切なバリアントを選択。
    ///
    /// # エラー
    ///
    /// - L2/L3 が 0 の場合(旧 bullet-shogi 形式): 明確なエラーメッセージを返す
    /// - サポートされていない L1 の場合: エラーを返す
    pub fn read<R: std::io::Read + std::io::Seek>(
        reader: &mut R,
        l1: usize,
        l2: usize,
        l3: usize,
        activation: Activation,
    ) -> std::io::Result<Self> {
        // 旧形式フォールバック削除: L2/L3 が 0 の場合はエラー
        if l2 == 0 || l3 == 0 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "HalfKA L1={l1} network missing L2/L3 dimensions in header. \
                     This is an old bullet-shogi format that is no longer supported. \
                     Please re-export the model with a newer version of bullet-shogi."
                ),
            ));
        }

        match l1 {
            256 => {
                let net = HalfKA_L256::read(reader, l2, l3, activation)?;
                Ok(Self::L256(net))
            }
            512 => {
                let net = HalfKA_L512::read(reader, l2, l3, activation)?;
                Ok(Self::L512(net))
            }
            768 => {
                let net = HalfKA_L768::read(reader, l2, l3, activation)?;
                Ok(Self::L768(net))
            }
            1024 => {
                let net = HalfKA_L1024::read(reader, l2, l3, activation)?;
                Ok(Self::L1024(net))
            }
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Unsupported HalfKA L1: {l1}"),
            )),
        }
    }

    /// L1 サイズを取得
    pub fn l1_size(&self) -> usize {
        match self {
            Self::L256(_) => 256,
            Self::L512(_) => 512,
            Self::L768(_) => 768,
            Self::L1024(_) => 1024,
        }
    }

    /// アーキテクチャ名を取得
    pub fn architecture_name(&self) -> &'static str {
        match self {
            Self::L256(net) => net.architecture_name(),
            Self::L512(net) => net.architecture_name(),
            Self::L768(net) => net.architecture_name(),
            Self::L1024(net) => net.architecture_name(),
        }
    }

    /// アーキテクチャ仕様を取得
    pub fn architecture_spec(&self) -> ArchitectureSpec {
        match self {
            Self::L256(net) => net.architecture_spec(),
            Self::L512(net) => net.architecture_spec(),
            Self::L768(net) => net.architecture_spec(),
            Self::L1024(net) => net.architecture_spec(),
        }
    }

    /// サポートするアーキテクチャ一覧
    pub fn supported_specs() -> Vec<ArchitectureSpec> {
        let mut specs = Vec::new();
        specs.extend_from_slice(HalfKA_L256::SUPPORTED_SPECS);
        specs.extend_from_slice(HalfKA_L512::SUPPORTED_SPECS);
        specs.extend_from_slice(HalfKA_L768::SUPPORTED_SPECS);
        specs.extend_from_slice(HalfKA_L1024::SUPPORTED_SPECS);
        specs
    }
}

/// HalfKA Accumulator スタック(L1 のみで決まる)
///
/// L2/L3/活性化の追加で変更不要。
pub enum HalfKAStack {
    L256(AccumulatorStackHalfKA<256>),
    L512(AccumulatorStackHalfKA<512>),
    L768(AccumulatorStackHalfKA<768>),
    L1024(AccumulatorStackHalfKA<1024>),
}

impl HalfKAStack {
    /// ネットワークに対応するスタックを生成
    ///
    /// バリアントマッチを使用し、新しい L1 追加時にコンパイル時に漏れ検知。
    pub fn from_network(net: &HalfKANetwork) -> Self {
        match net {
            HalfKANetwork::L256(_) => Self::L256(AccumulatorStackHalfKA::<256>::new()),
            HalfKANetwork::L512(_) => Self::L512(AccumulatorStackHalfKA::<512>::new()),
            HalfKANetwork::L768(_) => Self::L768(AccumulatorStackHalfKA::<768>::new()),
            HalfKANetwork::L1024(_) => Self::L1024(AccumulatorStackHalfKA::<1024>::new()),
        }
    }

    /// L1 サイズを取得
    pub fn l1_size(&self) -> usize {
        match self {
            Self::L256(_) => 256,
            Self::L512(_) => 512,
            Self::L768(_) => 768,
            Self::L1024(_) => 1024,
        }
    }

    /// スタックをリセット
    pub fn reset(&mut self) {
        match self {
            Self::L256(s) => s.reset(),
            Self::L512(s) => s.reset(),
            Self::L768(s) => s.reset(),
            Self::L1024(s) => s.reset(),
        }
    }

    /// ply を進める
    pub fn push(&mut self, dirty: DirtyPiece) {
        match self {
            Self::L256(s) => s.push(dirty),
            Self::L512(s) => s.push(dirty),
            Self::L768(s) => s.push(dirty),
            Self::L1024(s) => s.push(dirty),
        }
    }

    /// ply を戻す
    pub fn pop(&mut self) {
        match self {
            Self::L256(s) => s.pop(),
            Self::L512(s) => s.pop(),
            Self::L768(s) => s.pop(),
            Self::L1024(s) => s.pop(),
        }
    }

    /// 現在のインデックスを取得
    pub fn current_index(&self) -> usize {
        match self {
            Self::L256(s) => s.current_index(),
            Self::L512(s) => s.current_index(),
            Self::L768(s) => s.current_index(),
            Self::L1024(s) => s.current_index(),
        }
    }

    /// 祖先を辿って使用可能なアキュムレータを探す
    pub fn find_usable_accumulator(&self) -> Option<(usize, usize)> {
        match self {
            Self::L256(s) => s.find_usable_accumulator(),
            Self::L512(s) => s.find_usable_accumulator(),
            Self::L768(s) => s.find_usable_accumulator(),
            Self::L1024(s) => s.find_usable_accumulator(),
        }
    }

    /// 現在のアキュムレータが計算済みかどうか
    #[inline]
    pub fn is_current_computed(&self) -> bool {
        match self {
            Self::L256(s) => s.current().accumulator.computed_accumulation,
            Self::L512(s) => s.current().accumulator.computed_accumulation,
            Self::L768(s) => s.current().accumulator.computed_accumulation,
            Self::L1024(s) => s.current().accumulator.computed_accumulation,
        }
    }

    /// 現在のエントリの previous インデックス
    #[inline]
    pub fn current_previous(&self) -> Option<usize> {
        match self {
            Self::L256(s) => s.current().previous,
            Self::L512(s) => s.current().previous,
            Self::L768(s) => s.current().previous,
            Self::L1024(s) => s.current().previous,
        }
    }

    /// 指定インデックスのエントリが計算済みかどうか
    #[inline]
    pub fn is_entry_computed(&self, idx: usize) -> bool {
        match self {
            Self::L256(s) => s.entry_at(idx).accumulator.computed_accumulation,
            Self::L512(s) => s.entry_at(idx).accumulator.computed_accumulation,
            Self::L768(s) => s.entry_at(idx).accumulator.computed_accumulation,
            Self::L1024(s) => s.entry_at(idx).accumulator.computed_accumulation,
        }
    }

    /// 現在のエントリの dirty piece を取得
    #[inline]
    pub fn current_dirty_piece(&self) -> DirtyPiece {
        match self {
            Self::L256(s) => s.current().dirty_piece,
            Self::L512(s) => s.current().dirty_piece,
            Self::L768(s) => s.current().dirty_piece,
            Self::L1024(s) => s.current().dirty_piece,
        }
    }
}

impl Default for HalfKAStack {
    fn default() -> Self {
        Self::L512(AccumulatorStackHalfKA::<512>::new())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nnue::spec::FeatureSet;

    #[test]
    fn test_halfka_stack_from_network_l1_size() {
        // L256 ネットワークを仮定したスタック
        let stack = HalfKAStack::L256(AccumulatorStackHalfKA::<256>::new());
        assert_eq!(stack.l1_size(), 256);

        let stack = HalfKAStack::L512(AccumulatorStackHalfKA::<512>::new());
        assert_eq!(stack.l1_size(), 512);

        let stack = HalfKAStack::L1024(AccumulatorStackHalfKA::<1024>::new());
        assert_eq!(stack.l1_size(), 1024);
    }

    #[test]
    fn test_supported_specs_combined() {
        let specs = HalfKANetwork::supported_specs();
        // 256: 1, 512: 3, 768: 1, 1024: 3
        assert_eq!(specs.len(), 8);

        // 全て HalfKA
        for spec in &specs {
            assert_eq!(spec.feature_set, FeatureSet::HalfKA);
        }
    }

    /// push/pop の対称性と状態の一貫性テスト(L256)
    #[test]
    fn test_push_pop_index_consistency_l256() {
        let mut stack = HalfKAStack::L256(AccumulatorStackHalfKA::<256>::new());
        let dirty = DirtyPiece::default();

        stack.reset();
        let initial_index = stack.current_index();

        stack.push(dirty);
        assert_eq!(stack.current_index(), initial_index + 1);

        stack.push(dirty);
        assert_eq!(stack.current_index(), initial_index + 2);

        stack.pop();
        assert_eq!(stack.current_index(), initial_index + 1);

        stack.pop();
        assert_eq!(stack.current_index(), initial_index);
    }

    /// push/pop の対称性と状態の一貫性テスト(L512)
    #[test]
    fn test_push_pop_index_consistency_l512() {
        let mut stack = HalfKAStack::L512(AccumulatorStackHalfKA::<512>::new());
        let dirty = DirtyPiece::default();

        stack.reset();
        let initial_index = stack.current_index();

        stack.push(dirty);
        assert_eq!(stack.current_index(), initial_index + 1);

        stack.pop();
        assert_eq!(stack.current_index(), initial_index);
    }

    /// push/pop の対称性と状態の一貫性テスト(L1024)
    #[test]
    fn test_push_pop_index_consistency_l1024() {
        let mut stack = HalfKAStack::L1024(AccumulatorStackHalfKA::<1024>::new());
        let dirty = DirtyPiece::default();

        stack.reset();
        let initial_index = stack.current_index();

        stack.push(dirty);
        assert_eq!(stack.current_index(), initial_index + 1);

        stack.pop();
        assert_eq!(stack.current_index(), initial_index);
    }

    /// deep push/pop テスト(探索木の深さをシミュレート)
    #[test]
    fn test_deep_push_pop() {
        let mut stack = HalfKAStack::default();
        let dirty = DirtyPiece::default();

        stack.reset();
        let initial_index = stack.current_index();

        // 探索木の深さをシミュレート
        const DEPTH: usize = 30;

        for i in 0..DEPTH {
            stack.push(dirty);
            assert_eq!(stack.current_index(), initial_index + i + 1);
        }

        for i in (0..DEPTH).rev() {
            stack.pop();
            assert_eq!(stack.current_index(), initial_index + i);
        }
    }

    /// アーキテクチャの仕様一覧の一貫性テスト
    #[test]
    fn test_architecture_spec_consistency() {
        for spec in HalfKANetwork::supported_specs() {
            assert_eq!(spec.feature_set, FeatureSet::HalfKA);
            assert!(spec.l1 == 256 || spec.l1 == 512 || spec.l1 == 768 || spec.l1 == 1024);
            assert!(spec.l2 > 0 && spec.l2 <= 128);
            assert!(spec.l3 > 0 && spec.l3 <= 128);
        }
    }
}