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
//! `CpuProvider` — single CPU execution provider (auto serial / rayon).
use super::ExecutionProvider;
use crate::base::{Result, Value};
use crate::ir::{Ir, ModelIr};
use crate::session::batch::{Batch, BatchCtx, BatchResult};
use std::collections::HashMap;
use std::sync::OnceLock;
/// Unified CPU execution provider — auto-chooses serial vs `rayon` sharding.
///
/// For `n < 256` or `n < num_threads*4` it runs serially (same as old `CpuSerial`);
/// otherwise it shards via `rayon::par_chunks(chunk_size)` where `chunk_size = 256.max(n / num_threads)`.
///
/// Each thread gets its own `&mut [Value]` slice via `with_value_buffer` and `Arc<Ir>` is `Send+Sync`.
///
/// # Performance
///
/// ~402 ns per row single, ~61 ns/row at 100k Arrow rows. Small batches avoid `rayon` overhead.
///
/// # Examples
///
/// ```
/// use pmmlruntime::session::providers::{CpuProvider, ExecutionProvider};
/// let p = CpuProvider::new();
/// assert_eq!(p.name(), "CPU");
/// ```
pub struct CpuProvider {
cached_map: OnceLock<HashMap<String, crate::base::FieldId>>,
}
impl CpuProvider {
/// Create a new CPU provider (no allocation until first `eval_row` for `MiningModel`).
///
/// # Examples
///
/// ```
/// use pmmlruntime::session::providers::{CpuProvider, ExecutionProvider};
/// let p = CpuProvider::new();
/// assert_eq!(p.name(), "CPU");
/// ```
pub fn new() -> Self {
Self {
cached_map: OnceLock::new(),
}
}
/// Get or initialize the cached `name -> FieldId` map from `Ir.field_names`.
fn get_or_init_map<'a>(&'a self, ir: &Ir) -> &'a HashMap<String, crate::base::FieldId> {
self.cached_map.get_or_init(|| {
let mut m = HashMap::new();
for (fid, name) in &ir.field_names {
m.insert(name.clone(), *fid);
}
m
})
}
}
impl Default for CpuProvider {
fn default() -> Self {
Self::new()
}
}
impl ExecutionProvider for CpuProvider {
fn name(&self) -> &str {
"CPU"
}
/// Evaluate a batch with auto serial / parallel sharding.
///
/// For `n < 256` or `n < num_threads*4` it runs serially; otherwise `par_chunks(chunk_size)`.
fn eval_batch(&self, ir: &Ir, batch: &dyn Batch, ctx: &BatchCtx) -> Result<BatchResult> {
use crate::base::field::ResultFeature;
use crate::session::batch::BatchResult;
if batch.is_empty() {
return Ok(BatchResult::Rows(Vec::new()));
}
let needed = ctx.max_field_id.max(ir.num_fields() + 4);
let n = batch.len();
let num_threads = rayon::current_num_threads().max(1);
if n < 256 || n < num_threads * 4 {
let mut results = Vec::with_capacity(n);
for row_idx in 0..n {
let out = crate::session::with_value_buffer(
needed,
|values| -> Result<HashMap<String, Value>> {
batch.materialize_row(row_idx, values, ctx)?;
if let ModelIr::GeneralRegression(gr) = &ir.model {
let (predicted, probs) =
crate::engine::models::evaluate_general_regression_with_probs(
gr,
&values[..needed],
&ir.field_names,
&ir.symbol_names,
ctx.name_to_id_std,
);
let mut output =
HashMap::with_capacity(ctx.output_fields.len().max(1) + 2);
for of in ctx.output_fields {
match of.feature {
ResultFeature::Probability => {
if let Some(cat_sid) = of.value {
if let Some(cat_str) = ctx
.symbol_names_vec
.get(cat_sid.0 as usize)
.filter(|s| !s.is_empty())
{
if let Some(p) = probs.get(cat_str) {
output.insert(
of.name.clone(),
Value::Continuous(*p),
);
continue;
}
}
}
output.insert(of.name.clone(), Value::Missing);
}
_ => {
output.insert(of.name.clone(), predicted);
}
}
}
if output.is_empty() {
output.insert("predictedValue".to_string(), predicted);
}
let mut final_out = output;
if let Some(tname) = ctx.target_name {
final_out.entry(tname.clone()).or_insert(predicted);
}
final_out
.entry("predictedValue".to_string())
.or_insert(predicted);
for (k, v) in &probs {
final_out.entry(k.clone()).or_insert(Value::Continuous(*v));
let prob_name = format!("Probability_{}", k);
final_out.entry(prob_name).or_insert(Value::Continuous(*v));
}
Ok(final_out)
} else {
let predicted = self.eval_row(ir, values)?;
let mut output =
HashMap::with_capacity(ctx.output_fields.len().max(1) + 2);
if ctx.output_fields.is_empty() {
output.insert("predictedValue".to_string(), predicted);
} else {
for of in ctx.output_fields {
match of.feature {
ResultFeature::PredictedValue => {
output.insert(of.name.clone(), predicted);
}
ResultFeature::Probability => {
output.insert(of.name.clone(), Value::Continuous(0.0));
}
_ => {
output.insert(of.name.clone(), predicted);
}
}
}
}
let mut final_out = output;
if let Some(tname) = ctx.target_name {
final_out.entry(tname.clone()).or_insert(predicted);
}
final_out
.entry("predictedValue".to_string())
.or_insert(predicted);
Ok(final_out)
}
},
)?;
results.push(out);
}
return Ok(BatchResult::Rows(results));
}
use rayon::prelude::*;
let chunk_size = 256.max(n / num_threads);
let indices: Vec<usize> = (0..n).collect();
let chunk_results: Result<Vec<Vec<HashMap<String, Value>>>> = indices
.par_chunks(chunk_size)
.map(|chunk| -> Result<Vec<HashMap<String, Value>>> {
let mut local = Vec::with_capacity(chunk.len());
for &row_idx in chunk {
let out = crate::session::with_value_buffer(
needed,
|values| -> Result<HashMap<String, Value>> {
batch.materialize_row(row_idx, values, ctx)?;
if let ModelIr::GeneralRegression(gr) = &ir.model {
let (predicted, probs) =
crate::engine::models::evaluate_general_regression_with_probs(
gr,
&values[..needed],
&ir.field_names,
&ir.symbol_names,
ctx.name_to_id_std,
);
let mut output =
HashMap::with_capacity(ctx.output_fields.len().max(1) + 2);
for of in ctx.output_fields {
match of.feature {
ResultFeature::Probability => {
if let Some(cat_sid) = of.value {
if let Some(cat_str) = ctx
.symbol_names_vec
.get(cat_sid.0 as usize)
.filter(|s| !s.is_empty())
{
if let Some(p) = probs.get(cat_str) {
output.insert(
of.name.clone(),
Value::Continuous(*p),
);
continue;
}
}
}
output.insert(of.name.clone(), Value::Missing);
}
_ => {
output.insert(of.name.clone(), predicted);
}
}
}
if output.is_empty() {
output.insert("predictedValue".to_string(), predicted);
}
let mut final_out = output;
if let Some(tname) = ctx.target_name {
final_out.entry(tname.clone()).or_insert(predicted);
}
final_out
.entry("predictedValue".to_string())
.or_insert(predicted);
for (k, v) in &probs {
final_out.entry(k.clone()).or_insert(Value::Continuous(*v));
let prob_name = format!("Probability_{}", k);
final_out.entry(prob_name).or_insert(Value::Continuous(*v));
}
Ok(final_out)
} else {
let predicted = self.eval_row(ir, values)?;
let mut output =
HashMap::with_capacity(ctx.output_fields.len().max(1) + 2);
if ctx.output_fields.is_empty() {
output.insert("predictedValue".to_string(), predicted);
} else {
for of in ctx.output_fields {
match of.feature {
ResultFeature::PredictedValue => {
output.insert(of.name.clone(), predicted);
}
ResultFeature::Probability => {
output.insert(
of.name.clone(),
Value::Continuous(0.0),
);
}
_ => {
output.insert(of.name.clone(), predicted);
}
}
}
}
let mut final_out = output;
if let Some(tname) = ctx.target_name {
final_out.entry(tname.clone()).or_insert(predicted);
}
final_out
.entry("predictedValue".to_string())
.or_insert(predicted);
Ok(final_out)
}
},
)?;
local.push(out);
}
Ok(local)
})
.collect();
let results = chunk_results?.into_iter().flatten().collect();
Ok(BatchResult::Rows(results))
}
/// Evaluate a single row.
fn eval_row(&self, ir: &Ir, values: &mut [Value]) -> Result<Value> {
if !ir.symbol_names.is_empty() {
crate::engine::transform::vm::vm_set_symbol_map(ir.symbol_names.clone());
}
if !ir.derived_fields.is_empty() {
crate::engine::eval_derived_fields(&ir.derived_fields, values)
.map_err(crate::base::error::PmmlError::InvalidValue)?;
}
let predicted = match &ir.model {
ModelIr::Tree(tree) => crate::engine::models::evaluate_tree(tree, values),
ModelIr::Regression(reg) => crate::engine::models::evaluate_regression(reg, values),
ModelIr::Mining(mining) => {
let name_to_id = self.get_or_init_map(ir);
crate::engine::models::evaluate_mining(
mining,
values,
&ir.field_names,
&ir.symbol_names,
name_to_id,
)
}
ModelIr::Scorecard(sc) => crate::engine::models::evaluate_scorecard(sc, values),
ModelIr::Clustering(cl) => crate::engine::models::evaluate_clustering(cl, values),
ModelIr::NaiveBayes(nb) => crate::engine::models::evaluate_naive_bayes(nb, values),
ModelIr::NearestNeighbor(nn) => crate::engine::models::evaluate_nearest_neighbor(
nn,
values,
Some(&ir.field_names),
Some(&ir.symbol_names),
),
ModelIr::SupportVectorMachine(svm) => {
crate::engine::models::evaluate_support_vector_machine(svm, values)
}
ModelIr::GeneralRegression(gr) => {
let name_to_id = self.get_or_init_map(ir);
crate::engine::models::evaluate_general_regression(
gr,
values,
&ir.field_names,
&ir.symbol_names,
name_to_id,
)
}
ModelIr::NeuralNetwork(nn) => {
crate::engine::models::evaluate_neural_network(nn, values)
}
ModelIr::Association(a) => crate::engine::models::evaluate_association(a, values),
ModelIr::RuleSet(r) => crate::engine::models::evaluate_rule_set(r, values),
ModelIr::AnomalyDetection(ad) => {
crate::engine::models::evaluate_anomaly_detection(ad, values)
}
ModelIr::Baseline(b) => crate::engine::models::evaluate_baseline(b, values),
ModelIr::GaussianProcess(gp) => {
crate::engine::models::evaluate_gaussian_process(gp, values)
}
ModelIr::Text(t) => {
crate::engine::models::evaluate_text(t, values, Some(&ir.symbol_names))
}
ModelIr::TimeSeries(ts) => crate::engine::models::evaluate_time_series(ts, values),
ModelIr::Sequence(s) => crate::engine::models::evaluate_sequence(s, values),
ModelIr::BayesianNetwork(bn) => {
crate::engine::models::evaluate_bayesian_network(bn, values)
}
};
Ok(predicted)
}
}
impl CpuProvider {
/// Evaluate a batch in parallel, chunked at 1024 rows (or `num_cpus` sharded).
///
/// Provided for direct use; `Session::run_batch` is the public API.
#[allow(dead_code)]
pub fn evaluate_batch_parallel(
&self,
ir: &Ir,
batch_values: &mut [Vec<Value>],
) -> Result<Vec<Value>> {
use rayon::prelude::*;
batch_values
.par_iter_mut()
.map(|values| self.evaluate(ir, values))
.collect()
}
}