forked from huggingface/candle
-
Notifications
You must be signed in to change notification settings - Fork 8
/
darknet.rs
312 lines (292 loc) · 10.3 KB
/
darknet.rs
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
use candle::{DType, Device, IndexOp, Result, Tensor};
use candle_nn::{batch_norm, conv2d, conv2d_no_bias, Func, Module, VarBuilder};
use std::collections::BTreeMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
#[derive(Debug)]
struct Block {
block_type: String,
parameters: BTreeMap<String, String>,
}
impl Block {
fn get(&self, key: &str) -> Result<&str> {
match self.parameters.get(key) {
None => candle::bail!("cannot find {} in {}", key, self.block_type),
Some(value) => Ok(value),
}
}
}
#[derive(Debug)]
pub struct Darknet {
blocks: Vec<Block>,
parameters: BTreeMap<String, String>,
}
impl Darknet {
fn get(&self, key: &str) -> Result<&str> {
match self.parameters.get(key) {
None => candle::bail!("cannot find {} in net parameters", key),
Some(value) => Ok(value),
}
}
}
struct Accumulator {
block_type: Option<String>,
parameters: BTreeMap<String, String>,
net: Darknet,
}
impl Accumulator {
fn new() -> Accumulator {
Accumulator {
block_type: None,
parameters: BTreeMap::new(),
net: Darknet {
blocks: vec![],
parameters: BTreeMap::new(),
},
}
}
fn finish_block(&mut self) {
match &self.block_type {
None => (),
Some(block_type) => {
if block_type == "net" {
self.net.parameters = self.parameters.clone();
} else {
let block = Block {
block_type: block_type.to_string(),
parameters: self.parameters.clone(),
};
self.net.blocks.push(block);
}
self.parameters.clear();
}
}
self.block_type = None;
}
}
pub fn parse_config<T: AsRef<Path>>(path: T) -> Result<Darknet> {
let file = File::open(path.as_ref())?;
let mut acc = Accumulator::new();
for line in BufReader::new(file).lines() {
let line = line?;
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line.trim();
if line.starts_with('[') {
if !line.ends_with(']') {
candle::bail!("line does not end with ']' {line}")
}
let line = &line[1..line.len() - 1];
acc.finish_block();
acc.block_type = Some(line.to_string());
} else {
let key_value: Vec<&str> = line.splitn(2, '=').collect();
if key_value.len() != 2 {
candle::bail!("missing equal {line}")
}
let prev = acc.parameters.insert(
key_value[0].trim().to_owned(),
key_value[1].trim().to_owned(),
);
if prev.is_some() {
candle::bail!("multiple value for key {}", line)
}
}
}
acc.finish_block();
Ok(acc.net)
}
enum Bl {
Layer(Box<dyn candle_nn::Module + Send + Sync>),
Route(Vec<usize>),
Shortcut(usize),
Yolo(usize, Vec<(usize, usize)>),
}
fn conv(vb: VarBuilder, index: usize, p: usize, b: &Block) -> Result<(usize, Bl)> {
let activation = b.get("activation")?;
let filters = b.get("filters")?.parse::<usize>()?;
let pad = b.get("pad")?.parse::<usize>()?;
let size = b.get("size")?.parse::<usize>()?;
let stride = b.get("stride")?.parse::<usize>()?;
let padding = if pad != 0 { (size - 1) / 2 } else { 0 };
let (bn, bias) = match b.parameters.get("batch_normalize") {
Some(p) if p.parse::<usize>()? != 0 => {
let bn = batch_norm(filters, 1e-5, vb.pp(format!("batch_norm_{index}")))?;
(Some(bn), false)
}
Some(_) | None => (None, true),
};
let conv_cfg = candle_nn::Conv2dConfig {
stride,
padding,
groups: 1,
dilation: 1,
};
let conv = if bias {
conv2d(p, filters, size, conv_cfg, vb.pp(format!("conv_{index}")))?
} else {
conv2d_no_bias(p, filters, size, conv_cfg, vb.pp(format!("conv_{index}")))?
};
let leaky = match activation {
"leaky" => true,
"linear" => false,
otherwise => candle::bail!("unsupported activation {}", otherwise),
};
let func = candle_nn::func(move |xs| {
let xs = conv.forward(xs)?;
let xs = match &bn {
Some(bn) => xs.apply_t(bn, false)?,
None => xs,
};
let xs = if leaky {
xs.maximum(&(&xs * 0.1)?)?
} else {
xs
};
Ok(xs)
});
Ok((filters, Bl::Layer(Box::new(func))))
}
fn upsample(prev_channels: usize) -> Result<(usize, Bl)> {
let layer = candle_nn::func(|xs| {
let (_n, _c, h, w) = xs.dims4()?;
xs.upsample_nearest2d(2 * h, 2 * w)
});
Ok((prev_channels, Bl::Layer(Box::new(layer))))
}
fn int_list_of_string(s: &str) -> Result<Vec<i64>> {
let res: std::result::Result<Vec<_>, _> =
s.split(',').map(|xs| xs.trim().parse::<i64>()).collect();
Ok(res?)
}
fn usize_of_index(index: usize, i: i64) -> usize {
if i >= 0 {
i as usize
} else {
(index as i64 + i) as usize
}
}
fn route(index: usize, p: &[(usize, Bl)], block: &Block) -> Result<(usize, Bl)> {
let layers = int_list_of_string(block.get("layers")?)?;
let layers: Vec<usize> = layers
.into_iter()
.map(|l| usize_of_index(index, l))
.collect();
let channels = layers.iter().map(|&l| p[l].0).sum();
Ok((channels, Bl::Route(layers)))
}
fn shortcut(index: usize, p: usize, block: &Block) -> Result<(usize, Bl)> {
let from = block.get("from")?.parse::<i64>()?;
Ok((p, Bl::Shortcut(usize_of_index(index, from))))
}
fn yolo(p: usize, block: &Block) -> Result<(usize, Bl)> {
let classes = block.get("classes")?.parse::<usize>()?;
let flat = int_list_of_string(block.get("anchors")?)?;
if flat.len() % 2 != 0 {
candle::bail!("even number of anchors");
}
let flat = flat.into_iter().map(|i| i as usize).collect::<Vec<_>>();
let anchors: Vec<_> = (0..(flat.len() / 2))
.map(|i| (flat[2 * i], flat[2 * i + 1]))
.collect();
let mask = int_list_of_string(block.get("mask")?)?;
let anchors = mask.into_iter().map(|i| anchors[i as usize]).collect();
Ok((p, Bl::Yolo(classes, anchors)))
}
fn detect(
xs: &Tensor,
image_height: usize,
classes: usize,
anchors: &[(usize, usize)],
) -> Result<Tensor> {
let (bsize, _channels, height, _width) = xs.dims4()?;
let stride = image_height / height;
let grid_size = image_height / stride;
let bbox_attrs = 5 + classes;
let nanchors = anchors.len();
let xs = xs
.reshape((bsize, bbox_attrs * nanchors, grid_size * grid_size))?
.transpose(1, 2)?
.contiguous()?
.reshape((bsize, grid_size * grid_size * nanchors, bbox_attrs))?;
let grid = Tensor::arange(0u32, grid_size as u32, &Device::Cpu)?;
let a = grid.repeat((grid_size, 1))?;
let b = a.t()?.contiguous()?;
let x_offset = a.flatten_all()?.unsqueeze(1)?;
let y_offset = b.flatten_all()?.unsqueeze(1)?;
let xy_offset = Tensor::cat(&[&x_offset, &y_offset], 1)?
.repeat((1, nanchors))?
.reshape((grid_size * grid_size * nanchors, 2))?
.unsqueeze(0)?
.to_dtype(DType::F32)?;
let anchors: Vec<f32> = anchors
.iter()
.flat_map(|&(x, y)| vec![x as f32 / stride as f32, y as f32 / stride as f32].into_iter())
.collect();
let anchors = Tensor::new(anchors.as_slice(), &Device::Cpu)?
.reshape((anchors.len() / 2, 2))?
.repeat((grid_size * grid_size, 1))?
.unsqueeze(0)?;
let ys02 = xs.i((.., .., 0..2))?;
let ys24 = xs.i((.., .., 2..4))?;
let ys4 = xs.i((.., .., 4..))?;
let ys02 = (candle_nn::ops::sigmoid(&ys02)?.add(&xy_offset)? * stride as f64)?;
let ys24 = (ys24.exp()?.mul(&anchors)? * stride as f64)?;
let ys4 = candle_nn::ops::sigmoid(&ys4)?;
let ys = Tensor::cat(&[ys02, ys24, ys4], 2)?;
Ok(ys)
}
impl Darknet {
pub fn height(&self) -> Result<usize> {
let image_height = self.get("height")?.parse::<usize>()?;
Ok(image_height)
}
pub fn width(&self) -> Result<usize> {
let image_width = self.get("width")?.parse::<usize>()?;
Ok(image_width)
}
pub fn build_model(&self, vb: VarBuilder) -> Result<Func> {
let mut blocks: Vec<(usize, Bl)> = vec![];
let mut prev_channels: usize = 3;
for (index, block) in self.blocks.iter().enumerate() {
let channels_and_bl = match block.block_type.as_str() {
"convolutional" => conv(vb.pp(index.to_string()), index, prev_channels, block)?,
"upsample" => upsample(prev_channels)?,
"shortcut" => shortcut(index, prev_channels, block)?,
"route" => route(index, &blocks, block)?,
"yolo" => yolo(prev_channels, block)?,
otherwise => candle::bail!("unsupported block type {}", otherwise),
};
prev_channels = channels_and_bl.0;
blocks.push(channels_and_bl);
}
let image_height = self.height()?;
let func = candle_nn::func(move |xs| {
let mut prev_ys: Vec<Tensor> = vec![];
let mut detections: Vec<Tensor> = vec![];
for (_, b) in blocks.iter() {
let ys = match b {
Bl::Layer(l) => {
let xs = prev_ys.last().unwrap_or(xs);
l.forward(xs)?
}
Bl::Route(layers) => {
let layers: Vec<_> = layers.iter().map(|&i| &prev_ys[i]).collect();
Tensor::cat(&layers, 1)?
}
Bl::Shortcut(from) => (prev_ys.last().unwrap() + prev_ys.get(*from).unwrap())?,
Bl::Yolo(classes, anchors) => {
let xs = prev_ys.last().unwrap_or(xs);
detections.push(detect(xs, image_height, *classes, anchors)?);
Tensor::new(&[0u32], &Device::Cpu)?
}
};
prev_ys.push(ys);
}
Tensor::cat(&detections, 1)
});
Ok(func)
}
}