Hybrid MOTOR_VORFLOP_FLOP_QUELLE=sharingan: Vorflop/Flop von SHARINGAN B-local-2e10 (ohne Suche), Turn/River Motor mit SHARINGAN-gefuehrten Ranges

- src/sharingan.rs: Bruecke zum Dienst sharingan-hybrid (127.0.0.1:47123, ein Prozess fuer alle Tische, startet sich selbst,
  wartet das Laden ab), Vertrag -> ActRequest wie sh6.py, Range je Vorflop-/Flopzug (1326 Haende, zwischengespeichert)
- dienst.rs: versuche gibt vor dem Turn seinen Zug zurueck (NL2 danach wie sonst); ranges_mit nimmt vor dem Turn seine
  P(Zug | Hand) statt sechs100-v2 (Gegner: Masse aller Erhoehungen, Held: naechste Groesse; fallback -> unsere Strategie)
- nur 6-max-Hauptmotor, 6 Plaetze, ohne Straddle/Splash/Antes
- fremd/sharingan: LICENSE und NOTICE (Apache-2.0, unveraendert), Kopie des Dienstes, HINWEIS.md
- aus: 144/144 bitgleich zur nachtlive-Grundseite b1 (8 Blaetter); an: 51/51 Entscheidungen vor dem Turn von SHARINGAN,
  act 9 ms Mittel, range p90 540 ms (hybrid/KARTE.md). Keine Messung, die laeuft im Buendel gegen shf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-29 12:55:47 +01:00
co-authored by Claude Opus 5.5
parent 916a8660d7
commit 2bf49fe07f
9 changed files with 851 additions and 1 deletions
@@ -0,0 +1,11 @@
# SHARINGAN im Hybrid-Motor
Schalter `MOTOR_VORFLOP_FLOP_QUELLE=sharingan` (Standard aus; Brücke `entscheiden/motor/src/sharingan.rs`).
- Herkunft: SHARINGAN von Marko Kraemer, https://github.com/markokraemer/poker-sharingan, Stand 6a11d9b4 (7.11.2026).
Gewichte: Fassung B-local-2e10 (`B-local-2e10.plcp`, MODEL_CARD: `license: apache-2.0`).
- Lizenz: Apache License 2.0, Text in `LICENSE`, Hinweise des Urhebers in `NOTICE` (beide unverändert übernommen).
- Unsere Änderung: `sharingan-hybrid.rs` ist ein neues Programm in seinem Baum (`sharingan-1/serve/src/bin/`), das seinen
`Core::decide` aufruft (Grundstrategie ohne Suche, nur 127.0.0.1, kein Netz, kein Arena-Client). Sein Code und seine Gewichte
sind sonst unverändert. Die Datei hier ist eine Kopie zum Nachvollziehen; gebaut wird sie in seinem Baum unter D:/pokerfreak-fremd.
- Nichts davon wird weitergegeben; Code und Gewichte bleiben auf diesem Rechner.
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Marko Kraemer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+37
View File
@@ -0,0 +1,37 @@
SHARINGAN
Copyright 2026 Marko Kraemer
Licensed under the Apache License, Version 2.0.
This product includes or derives from the following third-party work:
* engine/iso is a Rust port of the hand-isomorphism indexer by Kevin Waugh
(https://github.com/kdub0/hand-isomorphism, `hand_index.c`; K. Waugh, "A Fast and
Optimal Hand Isomorphism Algorithm", 2013), distributed under this notice:
Copyright (c) 2013 Kevin Waugh (waugh@cs.cmu.edu).
All rights reserved.
Redistribution and use in source and binary forms are permitted
provided that the above copyright notice and this paragraph are
duplicated in all such forms and that any documentation,
advertising materials, and other materials related to such
distribution and use acknowledge that the software was developed
by the <organization>. The name of the
<organization> may not be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The hand-isomorphism indexer was developed by Kevin Waugh.
External tools that are used as opponents or data but are NOT redistributed here:
* RLCard (https://github.com/datamllab/rlcard, MIT): arena/adapters/rlcard_*.py are our own
bridge/training scripts that import it at runtime.
* PokerBench (HF `RZ412/PokerBench`, Apache-2.0 per its dataset card): download it separately.
* SvanBot (https://github.com/SvanLabs/SvanBot, Apache-2.0): arena/adapters/svan/extbridge.rs is our own
glue code that links against SvanBot's crates at build time; SvanBot's source is not included.
* Open Poker (openpoker.ai) and Slumbot (slumbot.com): public services used through their APIs.
The Pluribus paper and supplement (Brown & Sandholm, Science 2019) are copyrighted by
their publisher and are not included.
@@ -0,0 +1,182 @@
//! pokerfreak-Zusatz (29.11.): SHARINGAN-Grundstrategie als geteilter Dienst fuer den Hybrid-Motor (MOTOR_VORFLOP_FLOP_QUELLE=sharingan).
//! Nur 127.0.0.1, kein Auth-Abruf, keine Suche (Aufruf mit --no-search). Ein Prozess fuer alle Tische eines Laufs.
//! Zeilen-JSON ueber TCP, je Verbindung ein Faden:
//! {"op":"act","req":<ActRequest>} -> {"ok":true,"response":<ActResponse>}
//! {"op":"range","req":<ActRequest>,"act":{"type":..,"to":..}}
//! -> {"ok":true,"p":[1326 Wahrscheinlichkeiten]}: je Lochkartenpaar (Reihenfolge a<b, Karten 0..51 = Rang*4+Farbe, Farben c d h s)
//! die Wahrscheinlichkeit, mit der die Grundstrategie am Punkt `req` (hero_seat = wer zieht) den echten Zug `act` waehlt.
//! Erhoehungen: Masse des Eintrags mit dem naechsten `to` (Verhaeltnis); mit "alle":true die Summe aller Erhoehungen. -1 = Paar kollidiert mit dem Brett,
//! -2 = Punkt nicht in seinem Baum (fallback/desync), dann keine Information.
//! {"op":"ping"} -> {"ok":true}
//! HYBRID_LEERLAUF_S (Standard 900): ohne offene Verbindung so lange still -> beenden (gibt den Speicher frei).
use rayon::prelude::*;
use serde_json::{json, Value};
use sharingan_serve::api::ActRequest;
use sharingan_serve::config::Config;
use sharingan_serve::decide::Core;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
static OFFEN: AtomicUsize = AtomicUsize::new(0);
static ZULETZT: AtomicU64 = AtomicU64::new(0);
fn jetzt() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
const RANG: &[u8] = b"23456789TJQKA";
const FARBE: &[u8] = b"cdhs";
fn name(k: usize) -> String {
format!("{}{}", RANG[k / 4] as char, FARBE[k % 4] as char)
}
fn range(core: &Core, pool: &rayon::ThreadPool, v: &Value) -> Value {
let Ok(mut req) = serde_json::from_value::<ActRequest>(v["req"].clone()) else {
return json!({"ok": false, "error": "bad_request"});
};
req.options.include_probs = true;
req.options.search = false;
req.options.sample = false;
req.options.seed = Some(1);
let kind = v["act"]["type"].as_str().unwrap_or("").to_string();
let to = v["act"]["to"].as_i64();
let alle = v["act"]["alle"] == true;
let brett: Vec<String> = req.board.clone();
let paare: Vec<(usize, usize)> = (0..52).flat_map(|a| (a + 1..52).map(move |b| (a, b))).collect();
let p: Vec<f64> = pool.install(|| {
paare
.par_iter()
.map(|&(a, b)| {
let (na, nb) = (name(a), name(b));
if brett.iter().any(|c| c.eq_ignore_ascii_case(&na) || c.eq_ignore_ascii_case(&nb)) {
return -1.0;
}
let mut r = req.clone();
r.hole_cards = vec![na, nb];
let Ok(o) = core.decide(&r, String::new()) else { return -2.0 };
if o.source != "blueprint" {
return -2.0;
}
let probs = o.probs.unwrap_or_default();
let erh = |k: &str| k == "raise" || k == "bet" || k == "all_in";
if erh(&kind) && alle {
probs.iter().filter(|x| x.kind == "raise").map(|x| x.p).sum()
} else if erh(&kind) {
let ziel = to.unwrap_or(0).max(1) as f64;
probs
.iter()
.filter(|x| x.kind == "raise")
.min_by(|x, y| {
let d = |t: Option<i64>| (t.unwrap_or(1).max(1) as f64 / ziel).ln().abs();
d(x.to).total_cmp(&d(y.to))
})
.map_or(0.0, |x| x.p)
} else {
// check und call fallen in seiner Ausgabe je nach Lage auf "check"/"call"; fold ohne Einsatz gibt es nicht
let passiv = |k: &str| k == "check" || k == "call";
probs.iter().filter(|x| if passiv(&kind) { passiv(x.kind) } else { x.kind == kind }).map(|x| x.p).sum()
}
})
.collect()
});
json!({"ok": true, "p": p})
}
fn bediene(core: Arc<Core>, pool: Arc<rayon::ThreadPool>, s: TcpStream) {
OFFEN.fetch_add(1, Ordering::SeqCst);
bediene_innen(core, pool, s);
ZULETZT.store(jetzt(), Ordering::SeqCst);
OFFEN.fetch_sub(1, Ordering::SeqCst);
}
fn bediene_innen(core: Arc<Core>, pool: Arc<rayon::ThreadPool>, s: TcpStream) {
let _ = s.set_nodelay(true);
let mut aus = match s.try_clone() {
Ok(x) => x,
Err(_) => return,
};
for line in BufReader::new(s).lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
continue;
}
let v: Value = serde_json::from_str(&line).unwrap_or(Value::Null);
let r = match v["op"].as_str() {
Some("ping") => json!({"ok": true}),
Some("act") => match serde_json::from_value::<ActRequest>(v["req"].clone()) {
Err(e) => json!({"ok": false, "error": e.to_string()}),
Ok(mut req) => {
req.options.search = false;
req.options.include_probs = false;
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| core.decide(&req, core.next_request_id()))) {
Ok(Ok(a)) => json!({"ok": true, "response": a}),
Ok(Err(e)) => json!({"ok": false, "error": e.body()}),
Err(_) => json!({"ok": false, "error": "panic"}),
}
}
},
Some("range") => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| range(&core, &pool, &v))).unwrap_or_else(|_| json!({"ok": false, "error": "panic"})),
_ => json!({"ok": false, "error": "op"}),
};
if writeln!(aus, "{r}").and_then(|_| aus.flush()).is_err() {
break;
}
}
}
fn main() {
let mut args: Vec<String> = std::env::args().skip(1).collect();
// --port <n> ist unser Schalter; der Rest geht an seine Config
let mut port = 47123u16;
if let Some(i) = args.iter().position(|a| a == "--port") {
port = args.get(i + 1).and_then(|x| x.parse().ok()).unwrap_or(port);
args.drain(i..(i + 2).min(args.len()));
}
if !args.iter().any(|a| a == "--no-auth") {
args.push("--no-auth".into());
}
if !args.iter().any(|a| a == "--no-search") {
args.push("--no-search".into());
}
let mut cfg = match Config::parse(&|k| std::env::var(k).ok(), &args) {
Ok(c) => c,
Err(e) => {
eprintln!("{e}");
std::process::exit(2);
}
};
cfg.arena_auth_url = None;
sharingan_serve::log::set_enabled(false);
// erst binden: laeuft schon einer, sofort beenden (kein zweites Laden der Tabelle)
let l = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
eprintln!("sharingan-hybrid: Port {port} belegt ({e}), beende");
std::process::exit(3);
}
};
let core = Arc::new(Core::new(&cfg).unwrap_or_else(|e| {
eprintln!("error: {e}");
std::process::exit(1)
}));
let faeden = std::env::var("HYBRID_FAEDEN").ok().and_then(|x| x.parse().ok()).unwrap_or(2);
let pool = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(faeden).build().unwrap());
eprintln!("sharingan-hybrid bereit auf 127.0.0.1:{port}");
let leer = std::env::var("HYBRID_LEERLAUF_S").ok().and_then(|x| x.parse::<u64>().ok()).unwrap_or(900);
ZULETZT.store(jetzt(), Ordering::SeqCst);
std::thread::spawn(move || loop {
std::thread::sleep(std::time::Duration::from_secs(5));
if OFFEN.load(Ordering::SeqCst) == 0 && jetzt().saturating_sub(ZULETZT.load(Ordering::SeqCst)) > leer {
eprintln!("sharingan-hybrid: {leer} s ohne Verbindung, beende");
std::process::exit(0);
}
});
for s in l.incoming().flatten() {
let (c, p) = (core.clone(), pool.clone());
std::thread::spawn(move || bediene(c, p, s));
}
}
+21 -1
View File
@@ -392,7 +392,21 @@ impl Motor {
a
}
/// Hybrid (MOTOR_VORFLOP_FLOP_QUELLE=sharingan): nur der 6-max-Hauptmotor ohne Straddle, Splash und Antes
fn hybrid(&self, q: &Value) -> bool {
crate::sharingan::an() && self.s.n == 6 && !self.s.straddle && self.s.splash == 0 && !self.s.ante && self.s.art != crate::spiel::Art::PushFold
&& Self::splash_tot(q) == 0.0 && Self::ante_tot(q) == 0.0 && !Self::ist_straddle(q) && q.get("eigen").is_none() && q.get("probeHand").is_none()
}
fn versuche(&self, q: &Value) -> Result<Value, String> {
let _hybrid = if crate::sharingan::an() { Some(crate::sharingan::Wache::setze(self.hybrid(q).then(|| crate::sharingan::Kontext::aus(q)).flatten())) } else { None };
if let Some(k) = _hybrid.as_ref().and_then(|_| crate::sharingan::kontext()) {
if matches!(q["street"].as_str(), Some("PREFLOP" | "FLOP")) {
if let Some(a) = crate::sharingan::zug(q, &k) {
return Ok(a);
}
}
}
let f = |k: &str| q[k].as_f64();
let bb = f("bigBlind").ok_or("bigBlind")?;
let geld = |x: f64| (x / bb * 100.0) as f32;
@@ -828,13 +842,15 @@ impl Motor {
// nie gespielte Wege (Limper, Nachposter): die gelernte Strategie ist dort kaum trainiert, ihre Deutung zaehlt wenig
let duenn = |z: &Zustand, code: u8| z.strasse == 0 && z.hoch == 100 && code == CALL && z.dran >= 2;
let limper = l.gepostet[p] || l.pfad.iter().any(|(z, c)| z.dran as usize == p && duenn(z, *c));
for (z, code) in &l.pfad {
for (k, (z, code)) in l.pfad.iter().enumerate() {
if z.dran as usize != p || z.strasse >= bis {
continue;
}
if l.gepostet[p] && z.strasse == 0 && z.hoch == 100 && *code == CALL {
continue;
}
// Hybrid: vor dem Turn fuehrt seine Strategie die Range (None, wenn aus)
let fremd_v = if crate::sharingan::an() { crate::sharingan::range_fuer(k, z.strasse, z.dran, fremd) } else { None };
let m = z.menue(&self.s);
let Some(i) = m.liste().iter().position(|x| x.code == *code) else { continue };
let st = z.strasse as usize;
@@ -851,6 +867,10 @@ impl Motor {
None => vorflop(a, b),
Some(t) => self.t.kl[g].klasse(st, t, (a, b)),
};
if let Some(fv) = &fremd_v {
v[h] = fv[h].max(0.0);
continue;
}
let alle = fremd && *code >= 2;
v[h] = self.st.hole(key, kl, m.n).map_or(1.0 / m.n as f32, |mut v| {
if !fremd {
+1
View File
@@ -4,6 +4,7 @@ mod dienst;
mod gedaechtnis;
mod gegenprobe;
mod schiedsrichter;
mod sharingan;
mod nachprobe;
mod gegner;
mod flopwert;
+365
View File
@@ -0,0 +1,365 @@
//! Hybrid (29.11.): Vorflop und Flop spielt die SHARINGAN-Grundstrategie B-local-2e10 ohne Suche, Turn und River rechnet der Motor.
//! Schalter MOTOR_VORFLOP_FLOP_QUELLE=sharingan, Standard aus (dann laeuft kein Code dieses Moduls ausser dem Schalter-Lesen).
//!
//! SHARINGAN (markokraemer/poker-sharingan) steht unter Apache-2.0: Code und Gewichte; LICENSE und NOTICE liegen in
//! `entscheiden/motor/fremd/sharingan/`. Gerufen wird unser Dienst `sharingan-hybrid` (ein Zusatz in seinem Baum,
//! sharingan-1/serve/src/bin/sharingan-hybrid.rs), ein Prozess fuer alle Tische, nur 127.0.0.1, ohne Netz.
//!
//! Zwei Dinge kommen von ihm:
//! 1. der eigene Zug vor dem Flop und auf dem Flop (`zug`), danach greifen NL2-Regeln und Ausbeute wie sonst;
//! 2. in der Range-Fuehrung (`ranges_mit`) die Wahrscheinlichkeit je Hand, mit der seine Strategie den echten Zug gewaehlt
//! haette (`range_fuer`), fuer jeden Zug vor dem Flop und auf dem Flop. Uebersetzung wie in seiner TRANSLATION.md:
//! Erhoehungen auf den naechsten Eintrag seines Menues (Verhaeltnis der Ziele), beim Gegner die Masse aller Erhoehungen
//! zusammen (wie unsere eigene Fuehrung); Check und Call sind ein passiver Zug. Liegt ein Punkt nicht in seinem Baum
//! (fallback), bleibt fuer diesen Zug unsere eigene Strategie.
//! Umgebung: MOTOR_SHARINGAN_ADRESSE (127.0.0.1:47123), MOTOR_SHARINGAN_EXE, MOTOR_SHARINGAN_ARGS (Start, falls keiner laeuft),
//! MOTOR_SHARINGAN_WARTEN (s, Laden abwarten, Standard 900), MOTOR_SHARINGAN_PROTOKOLL=<datei>: je Frage `op ms ok` anhaengen.
use serde_json::{json, Value};
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::rc::Rc;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use crate::karten::{paar, HAENDE};
pub fn an() -> bool {
static AN: OnceLock<bool> = OnceLock::new();
*AN.get_or_init(|| std::env::var("MOTOR_VORFLOP_FLOP_QUELLE").is_ok_and(|x| x == "sharingan"))
}
const RANG: &[u8] = b"23456789TJQKA";
const FARBE: &[u8] = b"cdhs";
fn karte(v: &Value) -> Option<String> {
const R: [&str; 13] = ["TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING", "ACE"];
const F: [&str; 4] = ["CLUBS", "DIAMONDS", "HEARTS", "SPADES"];
let r = R.iter().position(|x| Some(*x) == v["rank"].as_str())?;
let f = F.iter().position(|x| Some(*x) == v["suit"].as_str())?;
Some(format!("{}{}", RANG[r] as char, FARBE[f] as char))
}
/// Ein echter Zug nach Vertrag, in seinen Begriffen
struct Zug {
strasse: u8,
/// Platz im Motor (ab SB)
sitz: u8,
/// Index in `hist`
j: usize,
/// fold / call / raise (ALL_IN unter dem Hoechsteinsatz = call)
art: &'static str,
to: Option<i64>,
}
pub struct Kontext {
basis: Value,
hist: Vec<Value>,
brett: Vec<String>,
zuege: Vec<Zug>,
}
thread_local! {
static JETZT: RefCell<Option<Rc<Kontext>>> = const { RefCell::new(None) };
}
/// Setzt den Kontext der laufenden Anfrage, stellt beim Verlassen den vorigen wieder her.
pub struct Wache(Option<Rc<Kontext>>);
impl Wache {
pub fn setze(k: Option<Kontext>) -> Wache {
Wache(JETZT.with(|j| j.replace(k.map(Rc::new))))
}
}
impl Drop for Wache {
fn drop(&mut self) {
let alt = self.0.take();
JETZT.with(|j| *j.borrow_mut() = alt);
}
}
pub fn kontext() -> Option<Rc<Kontext>> {
JETZT.with(|j| j.borrow().clone())
}
impl Kontext {
/// Vertrag -> seine ActRequest (BB = 100 Chips, Sitze 0..5 in Tischreihenfolge, `to` = Einsatz dieser Strasse,
/// stack_start = Stapel jetzt + eingezahlt). Nur volle sechs Plaetze, keine Antes; sonst None (dann spielt der Motor).
pub fn aus(q: &Value) -> Option<Kontext> {
let bb = q["bigBlind"].as_f64()?;
let c = |x: f64| (x / bb * 100.0).round() as i64;
let hist_q = q["history"].as_array()?;
let held = q["heroSeat"].as_i64()?;
let mut sitze: Vec<i64> = q["villains"].as_array()?.iter().filter_map(|v| v["seat"].as_i64()).collect();
sitze.push(held);
sitze.extend(hist_q.iter().filter_map(|h| h["seat"].as_i64()));
sitze.sort_unstable();
sitze.dedup();
if sitze.len() != 6 {
return None;
}
let pos = |s: i64| sitze.iter().position(|&x| x == s);
let sb = pos(hist_q.iter().find(|h| h["action"] == "POST_SB")?["seat"].as_i64()?)?;
let bbs = pos(hist_q.iter().find(|h| h["action"] == "POST_BB")?["seat"].as_i64()?)?;
if bbs != (sb + 1) % 6 || hist_q.iter().filter(|h| h["action"] == "POST_BB").count() != 1 {
return None;
}
let strasse_nr = |s: &str| ["PREFLOP", "FLOP", "TURN", "RIVER"].iter().position(|x| *x == s).map(|x| x as u8);
let (mut hist, mut zuege, mut drin) = (Vec::new(), Vec::new(), [0i64; 6]);
let (mut st, mut auf, mut hoch) = (0u8, [0i64; 6], 0i64);
for h in hist_q {
let x = h["action"].as_str()?;
let s = pos(h["seat"].as_i64()?)?;
let strasse = strasse_nr(h["street"].as_str().unwrap_or("PREFLOP"))?;
if strasse != st {
(st, auf, hoch) = (strasse, [0; 6], 0);
}
let typ = match x {
"POST_SB" => "post_sb",
"POST_BB" => "post_bb",
"FOLD" => "fold",
"CHECK" => "check",
"CALL" => "call",
"BET" => "bet",
"RAISE" => "raise",
"ALL_IN" => "all_in",
_ => return None,
};
let mut e = json!({"seat": s, "type": typ});
let mut to = None;
if matches!(x, "POST_SB" | "POST_BB" | "BET" | "RAISE" | "ALL_IN" | "CALL") {
if let Some(a) = h["amount"].as_f64() {
let t = c(a);
drin[s] += t - auf[s];
auf[s] = t;
if x != "CALL" {
e["to"] = json!(t);
to = Some(t);
}
}
}
if !x.starts_with("POST") {
let art = match x {
"FOLD" => "fold",
"CHECK" | "CALL" => "call",
_ if to.unwrap_or(0) <= hoch => "call",
_ => "raise",
};
zuege.push(Zug { strasse, sitz: ((s + 6 - sb) % 6) as u8, j: hist.len(), art, to });
}
if let Some(t) = to {
hoch = hoch.max(t);
}
hist.push(e);
}
let mut stand = [None; 6];
stand[pos(held)?] = q["heroStack"].as_f64().map(c);
for v in q["villains"].as_array()? {
if let (Some(s), Some(x)) = (v["seat"].as_i64().and_then(pos), v["stack"].as_f64()) {
stand[s] = Some(c(x));
}
}
let mut spieler = Vec::new();
for s in 0..6 {
spieler.push(json!({"seat": s, "stack_start": stand[s]? + drin[s]}));
}
let brett: Vec<String> = ["FLOP", "TURN", "RIVER"].iter().flat_map(|s| q["board"][*s].as_array().into_iter().flatten().filter_map(karte)).collect();
let loch: Vec<String> = q["heroCards"].as_array()?.iter().filter_map(karte).collect();
let seed = q["seed"].as_u64().unwrap_or(1);
let basis = json!({"small_blind": 50, "big_blind": 100, "button_seat": (sb + 5) % 6, "hero_seat": pos(held)?, "hole_cards": loch,
"board": brett, "players": spieler, "history": hist, "options": {"seed": seed, "include_probs": false}});
Some(Kontext { basis, hist, brett, zuege })
}
}
struct Leitung {
lesen: BufReader<TcpStream>,
schreiben: TcpStream,
}
static LEITUNG: Mutex<Option<Leitung>> = Mutex::new(None);
fn adresse() -> String {
std::env::var("MOTOR_SHARINGAN_ADRESSE").unwrap_or_else(|_| "127.0.0.1:47123".into())
}
fn verbinde() -> std::io::Result<Leitung> {
let a: std::net::SocketAddr = adresse().parse().map_err(|_| std::io::Error::other("Adresse"))?;
let s = TcpStream::connect_timeout(&a, Duration::from_millis(500))?;
s.set_nodelay(true)?;
s.set_read_timeout(Some(Duration::from_secs(120)))?;
Ok(Leitung { lesen: BufReader::new(s.try_clone()?), schreiben: s })
}
/// Laeuft kein Dienst: einen starten (losgeloest, BelowNormal, ohne Fenster) und das Laden abwarten. Starten mehrere Motoren
/// zugleich, beendet sich jeder spaetere Dienst sofort (Port belegt), bevor er die Tabelle laedt.
fn starte_und_warte() -> std::io::Result<Leitung> {
let frist = std::env::var("MOTOR_SHARINGAN_WARTEN").ok().and_then(|x| x.parse().ok()).unwrap_or(900u64);
// der Dienst bindet vor dem Laden: Verbindung steht sofort, die erste Antwort erst nach dem Laden
let bereit = |mut l: Leitung| -> std::io::Result<Leitung> {
l.schreiben.set_read_timeout(Some(Duration::from_secs(frist)))?;
writeln!(l.schreiben, "{{\"op\":\"ping\"}}")?;
let mut z = String::new();
l.lesen.read_line(&mut z)?;
l.schreiben.set_read_timeout(Some(Duration::from_secs(120)))?;
if z.contains("true") { Ok(l) } else { Err(std::io::Error::other("ping")) }
};
if let Ok(l) = verbinde() {
return bereit(l);
}
static GESTARTET: OnceLock<()> = OnceLock::new();
GESTARTET.get_or_init(|| {
const F: &str = "D:/pokerfreak-fremd/sharingan";
let exe = std::env::var("MOTOR_SHARINGAN_EXE").unwrap_or_else(|_| format!("{F}/code/target/serve/pokerbench-pruef6-hybrid.exe"));
let args = std::env::var("MOTOR_SHARINGAN_ARGS")
.unwrap_or_else(|_| format!("--blueprint {F}/weights/B-local-2e10.plcp --buckets {F}/data/buckets-200 --sizing local"));
let mut c = std::process::Command::new(exe);
c.args(args.split_whitespace()).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
if let Some(port) = adresse().rsplit(':').next() {
c.args(["--port", port]);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// DETACHED_PROCESS | CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS | CREATE_BREAKAWAY_FROM_JOB
c.creation_flags(0x8 | 0x0800_0000 | 0x4000 | 0x0100_0000);
if c.spawn().is_err() {
c.creation_flags(0x8 | 0x0800_0000 | 0x4000);
let _ = c.spawn();
}
}
#[cfg(not(windows))]
let _ = c.spawn();
});
let t0 = Instant::now();
loop {
match verbinde() {
Ok(l) => return bereit(l),
Err(e) if t0.elapsed().as_secs() > frist => return Err(e),
Err(_) => std::thread::sleep(Duration::from_millis(500)),
}
}
}
fn protokoll(op: &str, t0: Instant, ok: bool) {
if let Ok(p) = std::env::var("MOTOR_SHARINGAN_PROTOKOLL") {
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(p) {
let _ = writeln!(f, "{op} {:.0} {}", t0.elapsed().as_secs_f64() * 1000.0, ok as u8);
}
}
}
/// Eine Frage an den Dienst (mit Protokoll)
fn frage(v: &Value) -> Option<Value> {
let t0 = Instant::now();
let r = frage_roh(v);
protokoll(v["op"].as_str().unwrap_or("?"), t0, r.is_some());
r
}
/// Eine Frage an den Dienst; bei kaputter Leitung einmal neu verbinden.
fn frage_roh(v: &Value) -> Option<Value> {
let mut g = LEITUNG.lock().unwrap_or_else(|e| e.into_inner());
for _ in 0..2 {
if g.is_none() {
*g = Some(starte_und_warte().ok()?);
}
let l = g.as_mut()?;
let mut zeile = String::new();
let ok = writeln!(l.schreiben, "{v}").and_then(|_| l.schreiben.flush()).and_then(|_| l.lesen.read_line(&mut zeile)).is_ok_and(|n| n > 0);
if ok {
if let Ok(r) = serde_json::from_str::<Value>(&zeile) {
return (r["ok"] == true).then_some(r);
}
}
*g = None;
}
None
}
/// Der eigene Zug von SHARINGAN, als Vertragsantwort. None: er weiss keinen (dann spielt der Motor).
pub fn zug(q: &Value, k: &Kontext) -> Option<Value> {
let r = frage(&json!({"op": "act", "req": k.basis}))?;
let o = &r["response"];
let a = &o["action"];
let bb = q["bigBlind"].as_f64()?;
let f = |x: &str| q[x].as_f64();
let legal = |x: &str| q["legalActions"].as_array().is_some_and(|l| l.iter().any(|y| y == x));
let offen = f("toCall").unwrap_or(0.0);
let (mut akt, mut groesse) = match a["type"].as_str()? {
"fold" => (if offen > 0.0 { "FOLD" } else { "CHECK" }, None),
"check" => ("CHECK", None),
"call" => (if offen > 0.0 { "CALL" } else { "CHECK" }, None),
"raise" | "bet" | "all_in" => {
let (min, max) = (f("minRaiseTo").unwrap_or(0.0), f("maxRaiseTo").unwrap_or(f64::MAX));
let ziel = a["to"].as_f64().map_or(max, |t| t * bb / 100.0);
("RAISE", Some(((ziel.clamp(min.min(max), max)) / bb * 100.0).round() / 100.0 * bb))
}
_ => return None,
};
if akt == "RAISE" && !legal("RAISE") {
(akt, groesse) = (if offen > 0.0 { "CALL" } else { "CHECK" }, None);
}
if let (Some(g), Some(erlaubt)) = (groesse, q["allowedSizes"].as_array()) {
groesse = erlaubt.iter().filter_map(|x| x.as_f64()).min_by(|a, b| (a - g).abs().total_cmp(&(b - g).abs())).or(groesse);
}
if !legal(akt) {
akt = if legal("CHECK") { "CHECK" } else if legal("CALL") && akt != "FOLD" { "CALL" } else { "FOLD" };
groesse = None;
}
Some(json!({"action": akt, "size": groesse, "confidence": 1,
"reason": format!("sharingan {} ({})", o["source"].as_str().unwrap_or("?"), o["street"].as_str().unwrap_or("?"))}))
}
type Vektor = Arc<Vec<f32>>;
static SPEICHER: OnceLock<Mutex<HashMap<String, Vektor>>> = OnceLock::new();
/// Seine Reihenfolge (a<b ueber 0..51) -> unsere (paar)
fn umordnung() -> &'static Vec<usize> {
static U: OnceLock<Vec<usize>> = OnceLock::new();
U.get_or_init(|| (0..52u8).flat_map(|a| (a + 1..52).map(move |b| paar(b, a))).collect())
}
/// Fuer Schritt `k` des Pfads (Zug k des echten Verlaufs): je Hand (unsere Reihenfolge) die Wahrscheinlichkeit seines
/// Zugs; < 0 = kollidiert mit dem Brett. None: aus, nicht vor dem Turn, Verlauf passt nicht, oder er weiss es nicht.
pub fn range_fuer(k: usize, strasse: u8, sitz: u8, alle: bool) -> Option<Vektor> {
let kx = kontext()?;
let z = kx.zuege.get(k)?;
if strasse > 1 || z.strasse != strasse || z.sitz != sitz {
return None;
}
let mut req = kx.basis.clone();
req["history"] = Value::Array(kx.hist[..z.j].to_vec());
req["board"] = json!(kx.brett[..if strasse == 0 { 0 } else { 3.min(kx.brett.len()) }]);
req["hero_seat"] = kx.hist[z.j]["seat"].clone();
req["hole_cards"] = json!(["2c", "2d"]);
let mut act = json!({"type": z.art, "to": z.to});
if alle && z.art == "raise" {
act["alle"] = json!(true);
}
let frage_v = json!({"op": "range", "req": req, "act": act});
let schluessel = frage_v.to_string();
let sp = SPEICHER.get_or_init(Default::default);
if let Some(v) = sp.lock().unwrap_or_else(|e| e.into_inner()).get(&schluessel) {
return Some(v.clone());
}
let r = frage(&frage_v)?;
let p = r["p"].as_array()?;
if p.len() != HAENDE || p.iter().any(|x| x.as_f64() == Some(-2.0)) {
return None;
}
let mut v = vec![0f32; HAENDE];
for (i, x) in p.iter().enumerate() {
v[umordnung()[i]] = x.as_f64().unwrap_or(-1.0) as f32;
}
let v = Arc::new(v);
let mut g = sp.lock().unwrap_or_else(|e| e.into_inner());
if g.len() > 20000 {
g.clear();
}
g.insert(schluessel, v.clone());
Some(v)
}
@@ -0,0 +1,20 @@
# Hybrid: Vorflop und Flop von SHARINGAN, Turn und River vom Motor (29.11.)
Status: **gebaut**. Gemessen wird nur im Bündel gegen shf (Auftrag Orchestrator 13:05: „bauen, Messung nur im Bündel“).
- Schalter: `MOTOR_VORFLOP_FLOP_QUELLE=sharingan`, Standard aus. Exe `pokerbench-pruef6-hybrid.exe`.
- Brücke: `entscheiden/motor/src/sharingan.rs`.
- Haken in `dienst.rs`: `versuche` gibt vor dem Turn seinen Zug zurück. `ranges_mit` führt vor dem Turn mit seiner Strategie.
- Dienst: `sharingan-hybrid` (Kopie und Lizenz unter `entscheiden/motor/fremd/sharingan/`, HINWEIS.md dort).
## Prüfungen (keine Messung)
| Prüfung | Ergebnis |
|---|---|
| Schalter aus, b1 Saat 55, 8 Blätter, Grund-Umgebung, gegen die nachtlive-Grundseite | 144/144 bitgleich (drei Baustände) |
| Schalter an, b1, 2 Blätter gegen sh | alle 51 Motor-Entscheidungen vor dem Turn von SHARINGAN, 0 Fehler, 0 Notfälle |
| Zeit, act | Mittel 9 ms, max 106 ms |
| Zeit, range (1326 Hände, 2 Fäden, zwischengespeichert) | p50 47 ms, p90 540 ms, max 586 ms |
| Speicher | ein Dienst für alle Tische; Tabelle gemappt, Working Set 0,3 GB, Seiten im Datei-Cache |
Daten: `daten/bitprobe/b1-hybrid-aus*.jsonl`, `b1-hybrid-an.jsonl`, `b1-hybrid-an.zeiten`.
Aufruf Bitprobe (aus dem Ordner sharingan): `python hybrid/bitprobe.py [datei]`.
@@ -0,0 +1,12 @@
# Bitprobe Hybrid (29.11.): Hybrid-Exe mit Schalter aus, Grund-Umgebung, 8 Blaetter von b1 (Saat 55) gegen die b1-Grundseite (nachtlive).
# Aufruf aus dem Ordner sharingan: python hybrid/bitprobe.py [datei]. Verglichen je (Blatt, Drehung, Platz): Karten, Lochkarten, X-Plaetze, alle Zuege, Ergebnis.
import json, sys
B = "daten/nacht/sh-3v3-b1--pokerbench-pruef6-nachtlive--basis.jsonl"
T = sys.argv[1] if len(sys.argv) > 1 else "daten/bitprobe/b1-hybrid-aus.jsonl"
key = lambda r: (r["blatt"], r["dreh"], r["platz"])
feld = lambda r: (r["karten"], r["loch"], r["xplaetze"], r["alle"], r["erg"])
basis = {key(r): feld(r) for r in map(json.loads, open(B, encoding="utf-8")) if r["blatt"] < 8}
teile = {key(r): feld(r) for r in map(json.loads, open(T, encoding="utf-8"))}
gleich = sum(basis.get(k) == v for k, v in teile.items())
print("Zeilen Grundseite (Blatt<8): %d, Hybrid aus: %d, gleich: %d, Schluessel gleich: %s" % (len(basis), len(teile), gleich, set(basis) == set(teile)))
print("BITGLEICH" if gleich == len(teile) == len(basis) and set(basis) == set(teile) else "ABWEICHUNG")