graph.rs 15.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

20 21
use std::{cmp, collections::HashMap, convert::TryFrom, iter::FromIterator, mem, str};

22
use failure::Error;
23 24 25
use nom::{alpha1, digit1, le_i32, le_i64, le_u16, le_u32, le_u64, le_u8, types::CompleteStr};
use serde;
use serde_json;
26 27 28 29
use tvm_common::{
    array::{DataType, TVMContext},
    ffi::{DLDataTypeCode_kDLFloat, DLDataTypeCode_kDLInt, DLDataTypeCode_kDLUInt, DLTensor},
    TVMArgValue,
30 31
};

32 33
use crate::{errors::GraphFormatError, Module, Storage, Tensor};

34 35 36 37 38 39 40 41 42 43
// @see `kTVMNDArrayMagic` in `ndarray.h`
const _NDARRAY_MAGIC: u64 = 0xDD5E40F096B4A13F;
// @see `kTVMNDArrayListMagic` in `graph_runtime.h`
const _NDARRAY_LIST_MAGIC: u64 = 0xF7E58D4F05049CB7;

/// A TVM computation graph.
///
/// # Examples
///
/// ```
44
/// let graph_json = fs::read_to_string("graph.json").unwrap();
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/// let graph = Graph::try_from(&graph_json).unwrap();
/// ```
#[derive(Serialize, Deserialize, Debug)]
pub struct Graph {
    pub nodes: Vec<Node>,
    pub arg_nodes: Vec<usize>,
    pub heads: Vec<Entry>,
    pub node_row_ptr: Option<Vec<usize>>,
    pub attrs: Option<HashMap<String, serde_json::Value>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Entry {
    pub id: usize,
    pub index: usize,
    pub version: usize,
}

impl Graph {
64
    fn entry_index(&self, entry: &Entry) -> Result<usize, GraphFormatError> {
65 66 67
        self.node_row_ptr
            .as_ref()
            .map(|nrp| nrp[entry.id] + entry.index)
68
            .ok_or_else(|| GraphFormatError::MissingField("node_row_ptr"))
69 70 71
    }

    /// Attempt to deserialize a JSON attribute to a type `T`.
72
    fn get_attr<T: serde::de::DeserializeOwned>(&self, attr: &str) -> Result<T, GraphFormatError> {
73 74 75
        Ok(serde_json::from_value::<T>(
            self.attrs
                .as_ref()
76
                .ok_or(GraphFormatError::MissingField("attrs"))?
77
                .get(attr)
78 79 80
                .ok_or_else(|| {
                    GraphFormatError::MissingAttr("graph".to_string(), attr.to_string())
                })?
81
                .to_owned(),
82 83
        )
        .map_err(|err| GraphFormatError::Parse(err.into()))?)
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Node {
    pub op: String,
    pub name: String,
    pub inputs: Vec<Entry>,
    pub attrs: Option<HashMap<String, String>>,
    pub control_deps: Option<Vec<Entry>>,
}

struct NodeAttrs {
    func_name: String,
    num_outputs: usize,
    flatten_data: bool,
}

102 103 104 105 106 107 108 109
macro_rules! get_node_attr {
    ($node:expr, $attrs:ident, $attr:literal) => {
        $attrs
            .get($attr)
            .ok_or_else(|| GraphFormatError::MissingAttr($node.to_owned(), $attr.to_owned()))
    };
}

110
impl Node {
111
    fn parse_attrs(&self) -> Result<NodeAttrs, Error> {
112 113 114
        let attrs = self
            .attrs
            .as_ref()
115
            .ok_or_else(|| GraphFormatError::MissingAttr(self.name.clone(), "attrs".to_owned()))?;
116
        Ok(NodeAttrs {
117 118 119
            func_name: get_node_attr!(self.name, attrs, "func_name")?.to_owned(),
            num_outputs: get_node_attr!(self.name, attrs, "num_outputs")?.parse::<usize>()?,
            flatten_data: get_node_attr!(self.name, attrs, "flatten_data")?.parse::<u8>()? == 1,
120 121 122 123 124 125
        })
    }
}

impl<'a> TryFrom<&'a String> for Graph {
    type Error = Error;
126
    fn try_from(graph_json: &String) -> Result<Self, self::Error> {
127 128 129 130 131 132 133
        let graph = serde_json::from_str(graph_json)?;
        Ok(graph)
    }
}

impl<'a> TryFrom<&'a str> for Graph {
    type Error = Error;
134
    fn try_from(graph_json: &'a str) -> Result<Self, Self::Error> {
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
        let graph = serde_json::from_str(graph_json)?;
        Ok(graph)
    }
}

/// A executor for a TVM computation graph.
///
/// # Examples
///
/// ```
/// use ndarray::Array;
///
/// let syslib = SystemLibModule::default(); // a provider of TVM functions
///
/// let mut params_bytes = Vec::new();
/// fs::File::open("graph.params").unwrap().read_to_end(&mut params_bytes).unwrap();
/// let params = tvm::runtime::load_param_dict(&params_bytes).unwrap();
///
/// let graph = Graph::try_from(&fs::read_to_string("graph.json").unwrap()).unwrap();
///
/// let mut exec = GraphExecutor::new(graph, &syslib).unwrap();
/// exec.load_params(params);
///
/// let x = Array::from_vec(vec![1f32, 2., 3., 4.]);
/// exec.set_input("data", x.into());
/// exec.run();
/// let output = exec.get_output(0).unwrap();
///
/// println!("{:#?}", Array::try_from(output).unwrap());
/// ```
pub struct GraphExecutor<'m, 't> {
    graph: Graph,
    op_execs: Vec<Box<Fn() + 'm>>,
    tensors: Vec<Tensor<'t>>,
}

unsafe impl<'m, 't> Send for GraphExecutor<'m, 't> {}

impl<'m, 't> GraphExecutor<'m, 't> {
174
    pub fn new<M: 'm + Module>(graph: Graph, lib: &'m M) -> Result<Self, Error> {
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        let tensors = Self::setup_storages(&graph)?;
        Ok(GraphExecutor {
            op_execs: Self::setup_op_execs(&graph, lib, &tensors)?,
            tensors: tensors,
            graph: graph,
        })
    }

    /// Runs the computation graph.
    pub fn run(&self) {
        self.op_execs.iter().for_each(|op_exec| {
            op_exec();
        });
    }

    /// Allocates `Storages` for each `storage_id` and returns `Tensor`s to hold each output.
191
    fn setup_storages<'a>(graph: &'a Graph) -> Result<Vec<Tensor<'t>>, Error> {
192 193 194 195 196 197 198 199 200 201
        let storage_ids = graph.get_attr::<(String, Vec<usize>)>("storage_id")?.1;
        let shapes = graph.get_attr::<(String, Vec<Vec<i64>>)>("shape")?.1;
        let dtypes = graph
            .get_attr::<(String, Vec<String>)>("dltype")?
            .1
            .iter()
            .map(|dltype| {
                if let Ok((_, dtype)) = tvm_str_to_type(CompleteStr(dltype)) {
                    Ok(dtype)
                } else {
202
                    Err(GraphFormatError::InvalidDLType(dltype.to_string()))
203 204
                }
            })
205
            .collect::<Result<Vec<DataType>, GraphFormatError>>()?;
206

207
        let align = dtypes.iter().map(|dtype| dtype.bits() as usize).max();
208 209
        let mut storage_num_bytes = vec![0usize; *storage_ids.iter().max().unwrap_or(&1) + 1];
        for (i, &storage_id) in storage_ids.iter().enumerate() {
210
            let dtype_size = dtypes[i].bits() * dtypes[i].lanes() >> 3;
211 212 213 214 215 216 217
            let nbytes = dtype_size * shapes[i].iter().product::<i64>() as usize;
            storage_num_bytes[storage_id] = cmp::max(nbytes, storage_num_bytes[storage_id]);
        }

        let mut storages: Vec<Storage> = storage_num_bytes
            .into_iter()
            .map(|nbytes| Storage::new(nbytes, align))
218
            .collect::<Result<Vec<Storage>, Error>>()?;
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

        let tensors = izip!(storage_ids, shapes, dtypes)
            .map(|(storage_id, shape, dtype)| {
                let storage = storages[storage_id].view();
                Tensor {
                    data: mem::replace(&mut storages[storage_id], storage),
                    ctx: TVMContext::default(),
                    dtype: dtype,
                    size: shape.iter().product::<i64>() as usize,
                    shape: shape,
                    strides: None,
                    byte_offset: 0,
                }
            })
            .collect();

        Ok(tensors)
    }

    /// Creates closures which represent the computation performed by this graph.
    fn setup_op_execs<M: 'm + Module>(
        graph: &Graph,
        lib: &'m M,
        tensors: &Vec<Tensor<'t>>,
243
    ) -> Result<Vec<Box<Fn() + 'm>>, Error> {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        ensure!(graph.node_row_ptr.is_some(), "Missing node_row_ptr.");
        let node_row_ptr = graph.node_row_ptr.as_ref().unwrap();

        let mut op_execs = Vec::new();
        for (i, node) in graph.nodes.iter().enumerate() {
            if node.op == "null" {
                continue;
            }
            ensure!(node.op == "tvm_op", "Only TVM ops are supported.");
            ensure!(node.attrs.is_some(), "Missing node attrs.");

            let attrs = node.parse_attrs()?;

            if attrs.func_name == "__nop" {
                continue;
            }

261 262 263 264
            let func = lib.get_function(&attrs.func_name).ok_or(format_err!(
                "Library is missing function {}",
                attrs.func_name
            ))?;
265 266 267 268 269 270 271 272 273 274
            let arg_indices = node
                .inputs
                .iter()
                .map(|entry| graph.entry_index(entry))
                .chain((0..attrs.num_outputs).map(|oi| Ok(node_row_ptr[i].clone() + oi)));

            let dl_tensors = arg_indices
                .map(|idx| {
                    let tensor = &tensors[idx?];
                    Ok(if attrs.flatten_data {
275
                        Tensor::as_dltensor(tensor, true /* flatten */)
276 277 278 279
                    } else {
                        DLTensor::from(tensor)
                    })
                })
280
                .collect::<Result<Vec<DLTensor>, Error>>()
281 282 283 284 285 286
                .unwrap();
            let op: Box<Fn()> = box move || {
                let args = dl_tensors
                    .iter()
                    .map(|t| t.into())
                    .collect::<Vec<TVMArgValue>>();
287
                func(&args).unwrap();
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
            };
            op_execs.push(op);
        }
        Ok(op_execs)
    }

    pub fn load_params(&mut self, params: HashMap<String, Tensor>) {
        params.into_iter().for_each(|(name, param)| {
            self.set_input(name, param);
        })
    }

    pub fn set_input<S: AsRef<str>>(&mut self, name: S, value: Tensor) {
        if let Some(idx) = self.get_input_index(name.as_ref()) {
            // TODO: consider `new_with_params` to avoid ever allocating
            let ptr = self.tensors[idx].data.as_ptr();
            let mut to_replace = self.tensors.iter_mut().filter(|t| t.data.as_ptr() == ptr);
305
            let owner = to_replace.nth(0).unwrap();
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
            if value.data.is_owned() {
                // FIXME: for no-copy, need setup_op_execs to not capture tensor ptr
                // mem::replace(&mut (*owner), value);
                // to_replace.for_each(|t| {
                //   panic!("replacing");
                //   t.data = owner.data.view();
                // });
                owner.copy(&value);
            } else {
                owner.copy(&value);
            }
        } else {
            println!("Unexpected input `{}`", name.as_ref());
        }
    }

    /// Returns the graph input with name `name`, if it exists.
    pub fn get_input<S: AsRef<str>>(&mut self, name: S) -> Option<&Tensor> {
        self.get_input_index(name.as_ref())
            .and_then(move |idx| Some(&self.tensors[idx]))
    }

    /// Returns the graph output with index `index`, if it exists.
    pub fn get_output(&self, idx: usize) -> Option<&Tensor> {
        let graph = &self.graph;
        graph.heads.get(idx).and_then(|entry| {
            graph
                .entry_index(entry)
                .map(|idx| self.tensors.get(idx))
                .unwrap_or(None)
        })
    }

    /// Returns the index for graph input with name `name`, if it exists.
    pub fn get_input_index<S: AsRef<str>>(&self, name: S) -> Option<usize> {
        let graph = &self.graph;
        (0..graph.nodes.len())
            .skip_while(|&i| graph.nodes[i].name != name.as_ref())
            .nth(0)
            .and_then(|i| {
                if graph.arg_nodes.iter().any(|&id| id == i) {
                    graph.node_row_ptr.as_ref().map(|nrp| nrp[i])
                } else {
                    None
                }
            })
    }
}

355
// Converts a string to TVM DLDataTypeCode. @see `String2TVMType` in packed_func.h
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
named!(
  tvm_str_to_type<CompleteStr, DataType>,
  do_parse!(
    type_name: alpha1 >>
    bits: digit1 >>
    lanes: opt!(tuple!(tag!("x"), digit1)) >>
    (DataType {
      code: match type_name {
        CompleteStr("int") => DLDataTypeCode_kDLInt,
        CompleteStr("uint") => DLDataTypeCode_kDLUInt,
        CompleteStr("float") => DLDataTypeCode_kDLFloat,
        _ => DLDataTypeCode_kDLFloat,
      } as usize,
      bits: bits.parse::<u8>().unwrap() as usize,
      lanes: match lanes {
        Some(lanes) => lanes.1.parse::<u16>().unwrap() as usize,
        None => 1,
      },
    })
  )
);

378
// Converts a bytes to String.
379 380 381 382 383 384 385
named!(
    name<String>,
    map_res!(length_bytes!(le_u64), |b: &[u8]| String::from_utf8(
        b.to_vec()
    ))
);

386
// Parses a TVMContext
387 388 389 390 391 392 393 394 395
named!(
  tvm_ctx<&[u8], TVMContext>,
  do_parse!(
    device_type: le_u32 >>
    device_id: le_i32 >>
    (TVMContext { device_type: device_type as usize, device_id: device_id as usize })
  )
);

396
// Parses a DataType
397 398 399 400 401 402 403 404 405 406
named!(
  data_type<&[u8], DataType>,
  do_parse!(
    code: le_u8 >>
    bits: le_u8 >>
    lanes: le_u16 >>
    (DataType { code: code as usize, bits: bits as usize, lanes: lanes as usize })
  )
);

407
// Parses a Tensor from a TVM array file.
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
named!(
    tensor<Tensor>,
    do_parse!(
        take!(8)
            >> bits!(tag_bits!(u64, 64, 0))
            >> ctx: tvm_ctx
            >> ndim: le_u32
            >> dtype: data_type
            >> shape: count!(map!(le_i64, |sz| sz as i64), ndim as usize)
            >> length: le_i64
            >> data: take!(length)
            >> (Tensor {
                data: Storage::from(data),
                ctx: ctx,
                dtype: dtype,
                size: shape.iter().product::<i64>() as usize,
                shape: shape,
                strides: None,
                byte_offset: 0,
            })
    )
);

431
// Parses a graph params dict from a params binary file.
432 433 434 435 436 437 438 439 440 441 442 443
named!(
    parse_param_dict<HashMap<String, Tensor>>,
    do_parse!(
        take!(8)
            >> bits!(tag_bits!(u64, 64, 0))
            >> names: length_count!(le_u64, name)
            >> tensors: length_count!(le_u64, tensor)
            >> (HashMap::from_iter(names.into_iter().zip(tensors.into_iter())))
    )
);

/// Loads a param dict saved using `nnvm.compiler.save_param_dict`.
444
pub fn load_param_dict(bytes: &[u8]) -> Result<HashMap<String, Tensor>, GraphFormatError> {
445
    if let Ok((remaining_bytes, param_dict)) = parse_param_dict(bytes) {
446
        if remaining_bytes.len() == 0 {
447
            Ok(param_dict)
448 449
        } else {
            Err(GraphFormatError::Params)
450 451
        }
    } else {
452
        Err(GraphFormatError::Params)
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_str_to_type() {
        assert_eq!(
            tvm_str_to_type(CompleteStr("float24")).unwrap().1,
            DataType {
                code: DLDataTypeCode_kDLFloat as usize,
                bits: 24,
                lanes: 1
            }
        );
        assert_eq!(
            tvm_str_to_type(CompleteStr("uint111x44")).unwrap().1,
            DataType {
                code: DLDataTypeCode_kDLUInt as usize,
                bits: 111,
                lanes: 44
            }
        );
    }
}