use crate::co::prelude::*;
use crate::layer::*;
use crate::solver::*;
use crate::solvers::SGDSolver;
use crate::util::*;
use std::rc::Rc;
use std::sync::{Arc, RwLock};
#[derive(Debug)]
pub struct Momentum<SolverB: IBackend + SolverOps<f32>> {
history: Vec<ArcLock<SharedTensor<f32>>>,
backend: Rc<SolverB>,
lr: SharedTensor<f32>,
momentum: SharedTensor<f32>,
}
impl<SolverB: IBackend + SolverOps<f32>> Momentum<SolverB> {
pub fn new(backend: Rc<SolverB>) -> Momentum<SolverB> {
Momentum {
history: Vec::new(),
backend: backend,
lr: SharedTensor::<f32>::new(&[1]),
momentum: SharedTensor::<f32>::new(&[1]),
}
}
}
impl<B: IBackend + SolverOps<f32>, NetB: IBackend + LayerOps<f32> + 'static> SGDSolver<B, NetB> for Momentum<B> {
fn compute_update_value(
&mut self,
config: &SolverConfig,
weight_gradient: &ArcLock<SharedTensor<f32>>,
history_blob_id: usize,
global_lr: &f32,
blob_lr: &f32,
) {
crate::weight::FillerType::Constant {
value: global_lr * blob_lr,
}
.fill(&mut self.lr);
crate::weight::FillerType::Constant { value: config.momentum }.fill(&mut self.momentum);
let backend = ISolver::<B, NetB>::backend(self);
let device = IBackend::device(backend);
let history_blob = &self.history[history_blob_id];
Axpby::axpby(
backend,
&self.lr,
&weight_gradient.read().unwrap(),
&self.momentum,
&mut history_blob.write().unwrap(),
)
.unwrap();
backend
.copy(&history_blob.read().unwrap(), &mut weight_gradient.write().unwrap())
.unwrap();
}
}
impl_isolver_sgd!(Momentum<SolverB>);