// Generated by BlyxTorch 0.5.0. Compile, import or inspect this Blyx source. // MIT OR Apache-2.0. Copyright Rahul Chaube and BlyxTorch contributors. // Portable f64 primitives and forward-mode automatic differentiation. pub fn btx_finite(x: f64) -> bool { x - x == 0.0 } pub fn btx_valid(v: vector, width: i64) -> bool { if len(v) != width { return false; } let mut i = 0; while i < width { if !btx_finite(at(v, i)) { return false; } i += 1; } true } // exp(-x) for finite x >= 0. Range reduction bounds the Taylor remainder. fn exp_decay(x: f64) -> f64 { if x >= 746.0 { return 0.0; } let mut r = -x; let mut levels = 0; while r < -0.35 { r *= 0.5; levels += 1; } let mut term = 1.0; let mut total = 1.0; let mut k = 1.0; while k <= 15.0 { term *= r / k; total += term; k += 1.0; } while levels > 0 { total *= total; levels -= 1; } total } pub fn btx_exp_shift(x: f64) -> f64 { if x > 0.0 { return 0.0 / 0.0; } exp_decay(-x) } // log(1+x), 0 <= x <= 1. The transformed series also retains very small x. fn log1p_unit(x: f64) -> f64 { let z = x / (2.0 + x); let zz = z * z; let mut term = z; let mut accum = z; let mut k = 3.0; while k <= 35.0 { term *= zz; accum += term / k; k += 2.0; } 2.0 * accum } // The softmax denominator is always finite and at least one. pub fn btx_log_sum(x: f64) -> f64 { if x < 1.0 || !btx_finite(x) { return 0.0 / 0.0; } let mut n = x; let mut offset = 0.0; while n >= 2.0 { n *= 0.5; offset += 0.6931471805599453; } offset + log1p_unit(n - 1.0) } pub fn btx_sqrt(x: f64) -> f64 { if x == 0.0 { return 0.0; } if x < 0.0 || !btx_finite(x) { return 0.0 / 0.0; } let mut z = x; let mut scale = 1.0; while z < 1.0 { z *= 4.0; scale *= 0.5; } while z > 4.0 { z *= 0.25; scale *= 2.0; } let mut r = 1.5; let mut i = 0; while i < 6 { r = 0.5 * (r + z / r); i += 1; } r * scale } pub fn btx_logistic(x: f64) -> f64 { if x >= 0.0 { return 1.0 / (1.0 + exp_decay(x)); } let q = exp_decay(-x); q / (1.0 + q) } pub fn btx_tanh_value(x: f64) -> f64 { if x < 0.0 { return -btx_tanh_value(-x); } if x < 0.00001 { return x * (1.0 - x*x/3.0); } let q = exp_decay(2.0*x); (1.0-q)/(1.0+q) } pub fn btx_relu_value(x: f64) -> f64 { if x > 0.0 { return x; } 0.0 } pub fn btx_softplus_value(x: f64) -> f64 { if x >= 0.0 { return x + log1p_unit(exp_decay(x)); } log1p_unit(exp_decay(-x)) } pub fn btx_bce_value(logit: f64, label: f64) -> f64 { if logit >= 0.0 { return (1.0-label)*logit + log1p_unit(exp_decay(logit)); } return -label*logit + log1p_unit(exp_decay(-logit)); } pub fn btx_bce_slope(logit: f64, label: f64) -> f64 { if logit >= 0.0 { return (1.0-label) - btx_logistic(-logit); } btx_logistic(logit) - label } pub fn bt_dual(value: f64, tangent: f64) -> vector { if !btx_finite(value) || !btx_finite(tangent) { return []; } [value, tangent] } pub fn bt_add(a: vector, b: vector) -> vector { if len(a) != 2 || len(b) != 2 { return []; } bt_dual(at(a,0)+at(b,0), at(a,1)+at(b,1)) } pub fn bt_sub(a: vector, b: vector) -> vector { if len(a) != 2 || len(b) != 2 { return []; } bt_dual(at(a,0)-at(b,0), at(a,1)-at(b,1)) } pub fn bt_mul(a: vector, b: vector) -> vector { if len(a) != 2 || len(b) != 2 { return []; } bt_dual(at(a,0)*at(b,0), at(a,1)*at(b,0) + at(a,0)*at(b,1)) } pub fn bt_div(a: vector, b: vector) -> vector { if len(a) != 2 || len(b) != 2 || at(b,0) == 0.0 { return []; } let v = at(a,0)/at(b,0); bt_dual(v, (at(a,1)-v*at(b,1))/at(b,0)) } pub fn bt_square(a: vector) -> vector { bt_mul(a, a) } pub fn bt_relu(a: vector) -> vector { if !btx_valid(a,2) { return []; } if at(a,0) > 0.0 { return a; } [0,0] } pub fn bt_tanh(a: vector) -> vector { if !btx_valid(a,2) { return []; } let v = btx_tanh_value(at(a,0)); bt_dual(v, (1.0-v)*(1.0+v)*at(a,1)) } pub fn bt_sigmoid(a: vector) -> vector { if !btx_valid(a,2) { return []; } let x = at(a,0); bt_dual(btx_logistic(x), btx_logistic(x)*btx_logistic(-x)*at(a,1)) } pub fn bt_softplus(a: vector) -> vector { if !btx_valid(a,2) { return []; } bt_dual(btx_softplus_value(at(a,0)), btx_logistic(at(a,0))*at(a,1)) } pub fn bt_bce_logits(a: vector, label: f64) -> vector { if !btx_valid(a,2) || !btx_finite(label) || label < 0.0 || label > 1.0 { return []; } bt_dual(btx_bce_value(at(a,0),label), btx_bce_slope(at(a,0),label)*at(a,1)) } // Shared source included in every generated model, so a model can run independently. use std::cli; use std::text; use std::fs; fn btx_error(message: str) { stderr_line(text_concat("blyxtorch: ",message)); process_exit(2); } fn btx_uint(word: str, upper: i64) -> i64 { if !text_is_number(word) { return -1; } let number=text_number(word); let mut lo=0; let mut hi=upper; while lo<=hi { let mid=lo+(hi-lo)/2; let v=at([mid],0); if number==v { return mid; } if number f64 { at([n],0) } fn btx_numeric_fields(fields: arglist, start: i64, n: i64) -> bool { if start<0 || args_len(fields) f64 { let mut value=at(p,base+nin*nout+j); let mut k=0; while k f64 { let mut total=0.0; let mut k=0; while k f64 { if a>0.0 { return 1.0; } 0.0 } fn btx_tanh_slope(a: f64) -> f64 { (1.0-a)*(1.0+a) } fn btx_sigmoid_slope(a: f64) -> f64 { a*(1.0-a) } fn btx_weight(seed: i64, index: i64, fan_sum: i64) -> f64 { let prime=2147483647; let mut z=((seed%prime+prime)%prime+104729*(index+1))%prime; z=(z*z+48271)%prime; z=(z*z+48271)%prime; (2.0*(btx_float(z)/2147483647.0)-1.0)*btx_sqrt(6.0/btx_float(fan_sum)) } fn btx_max(z: vector) -> f64 { let mut m=at(z,0); let mut i=1; while im { m=at(z,i); } i+=1; } m } fn btx_exp_sum(z: vector, m: f64) -> f64 { let mut s=0.0; let mut i=0; while i f64 { if target==btx_float(index) { return 1.0; } 0.0 } fn btx_target_ok(t: vector) -> bool { if !btx_valid(t,bt_targets()) { return false; } if bt_objective()=="binary" { return at(t,0)>=0.0 && at(t,0)<=1.0; } if bt_objective()=="softmax" { let v=at(t,0); return v>=0.0 && v f64 { if bt_objective()=="binary" { return btx_bce_value(at(z,0),at(t,0)); } if bt_objective()=="softmax" { let m=btx_max(z); let s=btx_exp_sum(z,m); let mut i=0; while btx_float(i)!=at(t,0) { i+=1; } return (m-at(z,i))+btx_log_sum(s); } let mut sum_sq=0.0; let mut i=0; while i f64 { let x=at(b,i+off); if square { return left*at(a,i)+right*x*x; } left*at(a,i)+right*x } fn btx_adam_at(p: vector,m: vector,v: vector,i: i64,rate: f64,c1: f64,c2: f64) -> f64 { at(p,i)-rate*(at(m,i)/c1)/(btx_sqrt(at(v,i)/c2)+0.00000001) } fn btx_names(prefix: str, size: i64) -> str { let mut fields=args_new(); let mut i=0; while i str { btx_names("x",bt_inputs()) } pub fn bt_training_header() -> str { let mut labels=btx_names("y",bt_targets()); if bt_objective()=="softmax" { labels="class"; } text_concat(text_concat(bt_feature_header(),","),labels) } fn btx_read(path: str, labelled: bool) -> arglist { let lines=text_lines(read_text(path)); if args_len(lines)<2 { btx_error("a CSV needs a header and at least one data row"); } let mut header=bt_feature_header(); if labelled { header=bt_training_header(); } if text_trim(args_at(lines,0))!=header { btx_error(text_concat("expected CSV header ",header)); } lines } fn btx_fields(lines: arglist, row: i64, labelled: bool) -> arglist { let fields=text_split(args_at(lines,row),","); let mut n=bt_inputs(); if labelled { n+=bt_targets(); } if args_len(fields)!=n { btx_error(text_concat("incorrect column count at line ",int_text(row+1))); } fields } fn btx_print_row(v: vector) { let mut i=0; while i0 { print!(","); } print!(at(v,i)); i+=1; } println!(); } fn btx_checkpoint(p: vector) { if !btx_valid(p,bt_parameters()) { btx_error("nonfinite model weights"); } println!(bt_model_key()); btx_print_row(p); } fn btx_restore(path: str) -> vector { let lines=text_lines(read_text(path)); if args_len(lines)!=2 || args_at(lines,0)!=bt_model_key() { btx_error("checkpoint model key or line count mismatch"); } let fields=text_split(args_at(lines,1),","); if args_len(fields)!=bt_parameters() { btx_error("incorrect checkpoint parameter count"); } let p=bt_parse_p(fields,0); if !btx_valid(p,bt_parameters()) { btx_error("invalid checkpoint weight"); } p } fn btx_arg(a: arglist, i: i64, fallback: str) -> str { if i vector { if args_len(a)<2 || args_len(a)>7 { btx_error("train DATA.csv [epochs] [rate] [batch] [adam|sgd] [seed]"); } let epochs=btx_uint(btx_arg(a,2,"100"),1000000); let eta=btx_arg(a,3,"0.03"); let batch=btx_uint(btx_arg(a,4,"32"),2147483647); let optimizer=btx_arg(a,5,"adam"); let seed=btx_uint(btx_arg(a,6,"7"),2147483646); if epochs<1 || batch<1 || seed<0 || !text_is_number(eta) || text_number(eta)<=0.0 { btx_error("epochs, rate and batch must be positive; seed must be a nonnegative integer"); } if optimizer!="adam" && optimizer!="sgd" { btx_error("optimizer must be adam or sgd"); } let lr=text_number(eta); let lines=btx_read(args_at(a,1),true); let mut p=bt_init(seed); let zero=bt_zeros(); let mut moment=zero; let mut variance=zero; let mut b1=1.0; let mut b2=1.0; let mut epoch=0; while epoch2 || seed<0 { btx_error("init needs an optional nonnegative integer seed"); } btx_checkpoint(bt_init(seed)); return; } if cmd=="train" { btx_checkpoint(btx_train(a)); return; } if cmd=="train-score" || cmd=="train-predict" { if args_len(a)<3 || args_len(a)>8 { btx_error("supply training CSV, evaluation CSV, then optional epochs, rate, batch, optimizer and seed"); } let training=args_concat(args_push(args_push(args_new(),"train"),args_at(a,1)),args_tail(a,3)); let weights=btx_train(training); if cmd=="train-score" { btx_eval(weights,args_at(a,2),"score"); } else { btx_eval(weights,args_at(a,2),"predict"); } return; } if cmd=="predict" || cmd=="score" || cmd=="gradient" { if args_len(a)!=3 { btx_error("predict, score and gradient each take CHECKPOINT and DATA.csv"); } btx_eval(btx_restore(args_at(a,1)),args_at(a,2),cmd); return; } btx_error(text_concat("unknown command: ",cmd)); } pub fn bt_inputs() -> i64 { 2 } pub fn bt_outputs() -> i64 { 1 } pub fn bt_targets() -> i64 { 1 } pub fn bt_parameters() -> i64 { 17 } pub fn bt_objective() -> str { "binary" } pub fn bt_model_key() -> str { "BlyxTorch/1 2,4,1 binary tanh" } fn bt_layer0(p: vector, a: vector) -> vector { [ btx_tanh_value(btx_affine(p, a, 0, 2, 4, 0)), btx_tanh_value(btx_affine(p, a, 0, 2, 4, 1)), btx_tanh_value(btx_affine(p, a, 0, 2, 4, 2)), btx_tanh_value(btx_affine(p, a, 0, 2, 4, 3)) ] } fn bt_layer1(p: vector, a: vector) -> vector { [ btx_affine(p, a, 12, 4, 1, 0) ] } fn bt_transform(z: vector) -> vector { [btx_logistic(at(z,0))] } fn bt_output_delta(z: vector, t: vector) -> vector { [btx_bce_slope(at(z,0),at(t,0))] } pub fn bt_init(seed: i64) -> vector { [ btx_weight(seed,0,6), btx_weight(seed,1,6), btx_weight(seed,2,6), btx_weight(seed,3,6), btx_weight(seed,4,6), btx_weight(seed,5,6), btx_weight(seed,6,6), btx_weight(seed,7,6), 0.0, 0.0, 0.0, 0.0 , btx_weight(seed,12,5), btx_weight(seed,13,5), btx_weight(seed,14,5), btx_weight(seed,15,5), 0.0 ] } fn bt_logits(p: vector, x: vector) -> vector { if !btx_valid(p,bt_parameters()) || !btx_valid(x,bt_inputs()) { return []; } let a0 = x; let a1 = bt_layer0(p, a0); if !btx_valid(a1, 4) { return []; } let a2 = bt_layer1(p, a1); if !btx_valid(a2, 1) { return []; } a2 } pub fn bt_predict(p: vector, x: vector) -> vector { let z=bt_logits(p,x); if len(z)==0 { return []; } bt_transform(z) } pub fn bt_sample_loss(p: vector, x: vector, t: vector) -> vector { if !btx_target_ok(t) { return []; } let z=bt_logits(p,x); if len(z)==0 { return []; } let cost=btx_cost(z,t); if !btx_finite(cost) { return []; } [cost] } pub fn bt_loss_grad(p: vector, x: vector, t: vector) -> vector { if !btx_target_ok(t) { return []; } if !btx_valid(p,bt_parameters()) || !btx_valid(x,bt_inputs()) { return []; } let a0 = x; let a1 = bt_layer0(p, a0); if !btx_valid(a1, 4) { return []; } let a2 = bt_layer1(p, a1); if !btx_valid(a2, 1) { return []; } let cost = btx_cost(a2,t); let d2 = bt_output_delta(a2,t); let d1 = [ btx_pull(d2, p, 12, 4, 0)*btx_tanh_slope(at(a1, 0)), btx_pull(d2, p, 12, 4, 1)*btx_tanh_slope(at(a1, 1)), btx_pull(d2, p, 12, 4, 2)*btx_tanh_slope(at(a1, 2)), btx_pull(d2, p, 12, 4, 3)*btx_tanh_slope(at(a1, 3)) ]; let gradient = [cost, at(d1,0)*at(a0,0), at(d1,0)*at(a0,1), at(d1,1)*at(a0,0), at(d1,1)*at(a0,1), at(d1,2)*at(a0,0), at(d1,2)*at(a0,1), at(d1,3)*at(a0,0), at(d1,3)*at(a0,1), at(d1,0), at(d1,1), at(d1,2), at(d1,3) , at(d2,0)*at(a1,0), at(d2,0)*at(a1,1), at(d2,0)*at(a1,2), at(d2,0)*at(a1,3), at(d2,0) ]; if !btx_valid(gradient,bt_parameters()+1) { return []; } gradient } fn bt_parse_x(fields: arglist, start: i64) -> vector { if !btx_numeric_fields(fields,start,2) { return []; } [text_number(args_at(fields,start+0)), text_number(args_at(fields,start+1))] } fn bt_parse_t(fields: arglist, start: i64) -> vector { if !btx_numeric_fields(fields,start,1) { return []; } [text_number(args_at(fields,start+0))] } fn bt_parse_p(fields: arglist, start: i64) -> vector { if !btx_numeric_fields(fields,start,17) { return []; } [text_number(args_at(fields,start+0)), text_number(args_at(fields,start+1)), text_number(args_at(fields,start+2)), text_number(args_at(fields,start+3)), text_number(args_at(fields,start+4)), text_number(args_at(fields,start+5)), text_number(args_at(fields,start+6)), text_number(args_at(fields,start+7)), text_number(args_at(fields,start+8)), text_number(args_at(fields,start+9)), text_number(args_at(fields,start+10)), text_number(args_at(fields,start+11)), text_number(args_at(fields,start+12)), text_number(args_at(fields,start+13)), text_number(args_at(fields,start+14)), text_number(args_at(fields,start+15)), text_number(args_at(fields,start+16))] } pub fn bt_zeros() -> vector { [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } fn bt_mix(a: vector, b: vector, off: i64, left: f64, right: f64, square: bool) -> vector { [btx_mix_at(a,b,0,off,left,right,square), btx_mix_at(a,b,1,off,left,right,square), btx_mix_at(a,b,2,off,left,right,square), btx_mix_at(a,b,3,off,left,right,square), btx_mix_at(a,b,4,off,left,right,square), btx_mix_at(a,b,5,off,left,right,square), btx_mix_at(a,b,6,off,left,right,square), btx_mix_at(a,b,7,off,left,right,square), btx_mix_at(a,b,8,off,left,right,square), btx_mix_at(a,b,9,off,left,right,square), btx_mix_at(a,b,10,off,left,right,square), btx_mix_at(a,b,11,off,left,right,square), btx_mix_at(a,b,12,off,left,right,square), btx_mix_at(a,b,13,off,left,right,square), btx_mix_at(a,b,14,off,left,right,square), btx_mix_at(a,b,15,off,left,right,square), btx_mix_at(a,b,16,off,left,right,square)] } fn bt_adam(p: vector, m: vector, v: vector, rate: f64, c1: f64, c2: f64) -> vector { [btx_adam_at(p,m,v,0,rate,c1,c2), btx_adam_at(p,m,v,1,rate,c1,c2), btx_adam_at(p,m,v,2,rate,c1,c2), btx_adam_at(p,m,v,3,rate,c1,c2), btx_adam_at(p,m,v,4,rate,c1,c2), btx_adam_at(p,m,v,5,rate,c1,c2), btx_adam_at(p,m,v,6,rate,c1,c2), btx_adam_at(p,m,v,7,rate,c1,c2), btx_adam_at(p,m,v,8,rate,c1,c2), btx_adam_at(p,m,v,9,rate,c1,c2), btx_adam_at(p,m,v,10,rate,c1,c2), btx_adam_at(p,m,v,11,rate,c1,c2), btx_adam_at(p,m,v,12,rate,c1,c2), btx_adam_at(p,m,v,13,rate,c1,c2), btx_adam_at(p,m,v,14,rate,c1,c2), btx_adam_at(p,m,v,15,rate,c1,c2), btx_adam_at(p,m,v,16,rate,c1,c2)] } fn main() { bt_command(cli_args()); }