Skip to content

Commit

Permalink
Make func cloneable. (huggingface#1137)
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurentMazare authored and EricLBuehler committed Oct 25, 2023
1 parent 4646ae2 commit 14cccf0
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 deletions.
2 changes: 1 addition & 1 deletion candle-examples/examples/yolo-v3/darknet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ pub fn parse_config<T: AsRef<Path>>(path: T) -> Result<Darknet> {
}

enum Bl {
Layer(Box<dyn candle_nn::Module + Send>),
Layer(Box<dyn candle_nn::Module + Send + Sync>),
Route(Vec<usize>),
Shortcut(usize),
Yolo(usize, Vec<(usize, usize)>),
Expand Down
12 changes: 7 additions & 5 deletions candle-nn/src/func.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
//! Layers defined by closures.
use candle::{Result, Tensor};
use std::sync::Arc;

/// A layer defined by a simple closure.
#[derive(Clone)]
pub struct Func<'a> {
#[allow(clippy::type_complexity)]
f: Box<dyn 'a + Fn(&Tensor) -> Result<Tensor> + Send>,
f: Arc<dyn 'a + Fn(&Tensor) -> Result<Tensor> + Send + Sync>,
}

impl<'a> std::fmt::Debug for Func<'a> {
Expand All @@ -15,9 +17,9 @@ impl<'a> std::fmt::Debug for Func<'a> {

pub fn func<'a, F>(f: F) -> Func<'a>
where
F: 'a + Fn(&Tensor) -> Result<Tensor> + Send,
F: 'a + Fn(&Tensor) -> Result<Tensor> + Send + Sync,
{
Func { f: Box::new(f) }
Func { f: Arc::new(f) }
}

impl<'a> super::Module for Func<'a> {
Expand All @@ -29,8 +31,8 @@ impl<'a> super::Module for Func<'a> {
impl<'a> Func<'a> {
pub fn new<F>(f: F) -> Self
where
F: 'a + Fn(&Tensor) -> Result<Tensor> + Send,
F: 'a + Fn(&Tensor) -> Result<Tensor> + Send + Sync,
{
Self { f: Box::new(f) }
Self { f: Arc::new(f) }
}
}
2 changes: 1 addition & 1 deletion candle-nn/src/sequential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl Sequential {
/// Appends a closure after all the current layers.
pub fn add_fn<F>(self, f: F) -> Self
where
F: 'static + Fn(&Tensor) -> Result<Tensor> + Send,
F: 'static + Fn(&Tensor) -> Result<Tensor> + Send + Sync,
{
self.add(super::func(f))
}
Expand Down

0 comments on commit 14cccf0

Please sign in to comment.