tvm
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
vm.h
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
24 #ifndef TVM_RUNTIME_VM_VM_H_
25 #define TVM_RUNTIME_VM_VM_H_
26 
28 #include <tvm/runtime/module.h>
29 #include <tvm/runtime/object.h>
31 #include <tvm/runtime/registry.h>
35 
36 #include <memory>
37 #include <string>
38 #include <unordered_map>
39 #include <utility>
40 #include <vector>
41 
42 namespace tvm {
43 namespace runtime {
44 namespace vm {
45 
49 class VMClosureObj : public ClosureObj {
50  public:
55  size_t func_index;
57  std::vector<ObjectRef> free_vars;
58 
59  static constexpr const uint32_t _type_index = TypeIndex::kDynamic;
60  static constexpr const char* _type_key = "vm.Closure";
62 };
63 
65 class VMClosure : public Closure {
66  public:
67  VMClosure(size_t func_index, std::vector<ObjectRef> free_vars);
69 };
70 
77 struct VMFunction {
79  std::string name;
81  std::vector<std::string> params;
83  std::vector<Instruction> instructions;
87  std::vector<Index> param_device_indexes;
88 
89  VMFunction(std::string name, std::vector<std::string> params,
90  std::vector<Instruction> instructions, Index register_file_size,
91  std::vector<Index> param_device_indexes)
92  : name(std::move(name)),
93  params(std::move(params)),
94  instructions(std::move(instructions)),
97  ICHECK_EQ(this->params.size(), this->param_device_indexes.size());
98  }
99 
100  VMFunction() = default;
101 
102  friend std::ostream& operator<<(std::ostream& os, const VMFunction&);
103 };
104 
112 struct VMFrame {
121 
123  std::vector<ObjectRef> register_file;
124 
127 
128  VMFrame(Index pc, Index func_index, Index args, const Instruction* code, Index register_file_size)
129  : pc(pc),
131  args(args),
132  code(code),
133  register_file(register_file_size),
135 };
136 
148 class TVM_DLL VirtualMachine : public runtime::ModuleNode {
149  public:
167  virtual PackedFunc GetFunction(const String& name, const ObjectPtr<Object>& sptr_to_self);
168 
169  virtual ~VirtualMachine() {}
170 
171  const char* type_key() const final { return "VirtualMachine"; }
172 
173  VirtualMachine() : frames_(), func_index_(0), code_(nullptr), pc_(0), exec_(nullptr) {}
174 
179  virtual void LoadExecutable(const ObjectPtr<Executable>& exec);
180 
182  int GetPropertyMask() const final { return ModulePropertyMask::kRunnable; }
183 
184  protected:
186  void PushFrame(Index arg_count, Index ret_pc, const VMFunction& vm_func);
187 
193 
199  inline void WriteRegister(RegName reg, const ObjectRef& obj);
200 
207 
213  int64_t LoadScalarInt(RegName reg) const;
214 
221  ObjectRef Invoke(const VMFunction& func, const std::vector<ObjectRef>& args);
222 
223  // TODO(@jroesch): I really would like this to be a global variable.
230  ObjectRef Invoke(const std::string& name, const std::vector<ObjectRef>& args);
231 
239  ObjectRef Invoke(const VMFunction& func, const std::vector<ObjectRef>& input_args,
240  const std::vector<ObjectRef>& output_args);
241 
253  virtual void InvokePacked(Index packed_index, const PackedFunc& func, Index arg_count,
254  Index output_size, const std::vector<ObjectRef>& args);
255 
261  void Init(const std::vector<Device>& physical_devices,
262  const std::vector<AllocatorType>& alloc_types);
263 
265  void RunLoop(const std::vector<Index>& output_tensor_reg_indices = {});
266 
268  Device GetDevice(Index device_index) const;
269  Allocator* GetAllocator(Index device_index) const;
270 
276  void InvokeGlobal(const VMFunction& func, const std::vector<ObjectRef>& args);
277 
286  void SetInput(std::string name, TVMArgs args, int offset);
287 
295  void SetOneInput(std::string name, const TVMArgValue& tag, const TVMArgValue& tensor);
296 
306  void SetOutputs(std::string name, TVMArgs args);
307 
313  void PrintInfoAndSetInputArgs(const VMFunction& func, const std::vector<ObjectRef>& args);
314 
320  void SetOutputTensorsToRegister(const std::string& func_name,
321  const std::vector<ObjectRef>& outputs);
322 
332  virtual void OpStartHook(Instruction instr);
333 
337  virtual void OpStopHook();
338 
339  private:
346  int64_t GetInputIndexFromVMFunction(const std::string& func_name,
347  const std::string& input_name) const;
348 
355  int64_t GetInputIndexFromName(const std::vector<std::string>& params,
356  const std::string& input_name) const;
357 
363  const VMFunction& CheckAndGetVMFunction(const std::string& func_name) const;
364 
370  void CreateInputsOrCheckSize(const std::string& func_name, size_t size);
371 
377  void SetInputTensorWithIndex(std::vector<ObjectRef>& tensors, // NOLINT(*)
378  const TVMArgValue& tensor, int index, Device dev);
379 
386  ObjectRef TensorFromTVMArgValueToObjectRef(const TVMArgValue& tensor) const;
387 
392  Index GetResultRegisterIndex() const;
393 
398  void CalculatePreResultOpIndex(Index res_index);
399 
406  std::vector<Index> GetOutputTensorRegIndices();
407 
412  void WriteAllocatedTensor(const Instruction& instr);
413 
421  void WriteAllocatedTensorFromOutside(const Instruction& instr);
422 
423  bool FindIndex(const std::vector<Index>& indices, Index val) const;
424 
425  protected:
427  std::vector<PackedFunc> packed_funcs_;
429  std::vector<VMFrame> frames_;
441  std::unordered_map<std::string, std::vector<ObjectRef>> inputs_;
443  std::unordered_map<std::string, bool> set_outputs_enabled_;
445  Index preresult_op_index_ = -1;
447  std::unordered_map<std::string, std::vector<Index>> output_tensor_reg_indices_;
449  std::unordered_map<std::string, std::vector<ObjectRef>> outputs_;
455  std::vector<Device> devices_;
457  std::vector<Allocator*> allocators_;
462  std::vector<ObjectRef> const_pool_;
463 };
464 
465 } // namespace vm
466 } // namespace runtime
467 } // namespace tvm
468 
469 #endif // TVM_RUNTIME_VM_VM_H_
The bytecode for Relay virtual machine.
An object representing a closure. This object is used by both the Relay VM and interpreter.
Definition: closure.h:36
reference to closure.
Definition: closure.h:44
Base container of module.
Definition: module.h:142
A custom smart pointer for Object.
Definition: object.h:358
Base class of all object reference.
Definition: object.h:515
Packed function is a type-erased function. The arguments are passed by packed format.
Definition: packed_func.h:138
Reference to string objects.
Definition: string.h:98
A single argument value to PackedFunc. Containing both type_code and TVMValue.
Definition: packed_func.h:646
Arguments into TVM functions.
Definition: packed_func.h:391
Definition: memory_manager.h:55
An object representing a vm closure.
Definition: vm.h:49
static constexpr const char * _type_key
Definition: vm.h:60
std::vector< ObjectRef > free_vars
The free variables of the closure.
Definition: vm.h:57
static constexpr const uint32_t _type_index
Definition: vm.h:59
TVM_DECLARE_FINAL_OBJECT_INFO(VMClosureObj, ClosureObj)
size_t func_index
The index into the function list. The function could be any function object that is compatible to the...
Definition: vm.h:55
reference to closure.
Definition: vm.h:65
VMClosure(size_t func_index, std::vector< ObjectRef > free_vars)
TVM_DEFINE_OBJECT_REF_METHODS(VMClosure, Closure, VMClosureObj)
The virtual machine.
Definition: vm.h:148
const char * type_key() const final
Definition: vm.h:171
void SetInput(std::string name, TVMArgs args, int offset)
Set inputs to a function.
void PushFrame(Index arg_count, Index ret_pc, const VMFunction &vm_func)
Push a call frame on to the call stack.
void RunLoop(const std::vector< Index > &output_tensor_reg_indices={})
Run VM dispatch loop.
std::vector< Allocator * > allocators_
The cached memory allocators, one per device.
Definition: vm.h:457
ObjectRef Invoke(const std::string &name, const std::vector< ObjectRef > &args)
Invoke a VM function by name.
int64_t LoadScalarInt(RegName reg) const
Read a VM register and cast it to int32_t.
void Init(const std::vector< Device > &physical_devices, const std::vector< AllocatorType > &alloc_types)
Initialize the virtual machine for a set of (physical) devices.
void SetOutputs(std::string name, TVMArgs args)
Set pre-allocated output tensors to a function. It is native implementation of 'set_outputs' python m...
void InvokeGlobal(const VMFunction &func, const std::vector< ObjectRef > &args)
Invoke a global setting up the VM state to execute.
ObjectRef ReadRegister(RegName reg) const
Read a VM register.
std::unordered_map< std::string, std::vector< ObjectRef > > outputs_
The function name to pre-allocated outputs mapping.
Definition: vm.h:449
std::vector< VMFrame > frames_
The current stack of call frames.
Definition: vm.h:429
virtual void OpStartHook(Instruction instr)
Internal hook for profiling the start of an op.
virtual void OpStopHook()
Internal hook for profiling the end of an op.
std::vector< ObjectRef > const_pool_
The constant pool for runtime. It caches the device dependent object to avoid rellocation of constant...
Definition: vm.h:462
Allocator * GetAllocator(Index device_index) const
virtual void LoadExecutable(const ObjectPtr< Executable > &exec)
load the executable for the virtual machine.
Index pc_
The virtual machine PC.
Definition: vm.h:435
Index PopFrame()
Pop a frame off the call stack.
std::vector< Device > devices_
The "physical" devices the VM can execute primitives on. All "device indexes" are w....
Definition: vm.h:455
ObjectPtr< Executable > exec_
The executable the VM will operate on.
Definition: vm.h:439
virtual ~VirtualMachine()
Definition: vm.h:169
Device GetDevice(Index device_index) const
Get device from the device list based on a given device index.
void WriteRegister(RegName reg, const ObjectRef &obj)
Write to a VM register.
std::unordered_map< std::string, bool > set_outputs_enabled_
The function name to flag enabling scenario with set outputs.
Definition: vm.h:443
ObjectRef Invoke(const VMFunction &func, const std::vector< ObjectRef > &input_args, const std::vector< ObjectRef > &output_args)
Invoke a VM function.
VirtualMachine()
Definition: vm.h:173
std::unordered_map< std::string, std::vector< ObjectRef > > inputs_
The function name to inputs mapping.
Definition: vm.h:441
virtual void InvokePacked(Index packed_index, const PackedFunc &func, Index arg_count, Index output_size, const std::vector< ObjectRef > &args)
Invoke a PackedFunction.
void SetOutputTensorsToRegister(const std::string &func_name, const std::vector< ObjectRef > &outputs)
Set pre-allocated outputs to register for specified function.
ObjectRef Invoke(const VMFunction &func, const std::vector< ObjectRef > &args)
Invoke a VM function.
std::unordered_map< std::string, std::vector< Index > > output_tensor_reg_indices_
The function name to indices of output tensors in register file.
Definition: vm.h:447
const Instruction * code_
The current pointer to the code section.
Definition: vm.h:433
void SetOneInput(std::string name, const TVMArgValue &tag, const TVMArgValue &tensor)
Set one input tensor with index or name to a function.
void PrintInfoAndSetInputArgs(const VMFunction &func, const std::vector< ObjectRef > &args)
Preparation part of Invoke method before RunLoop.
int GetPropertyMask() const final
Get the property of the runtime module .
Definition: vm.h:182
virtual PackedFunc GetFunction(const String &name, const ObjectPtr< Object > &sptr_to_self)
Get a PackedFunc from module.
std::vector< PackedFunc > packed_funcs_
The virtual machine's packed function table.
Definition: vm.h:427
Index func_index_
The fuction table index of the current function.
Definition: vm.h:431
ObjectRef return_register_
The special return register.
Definition: vm.h:437
Runtime Closure container types.
The Relay virtual machine executable.
Abstract device memory management API.
int64_t Index
An alias for the integer type used ubiquitously in the VM.
Definition: bytecode.h:43
int64_t RegName
A register name.
Definition: bytecode.h:38
@ kRunnable
kRunnable we can run the module directly. LLVM/CUDA/JSON runtime, executors (e.g, virtual machine) ru...
Definition: module.h:62
runtime implementation for LibTorch/TorchScript.
Definition: analyzer.h:36
DLDevice Device
Definition: ndarray.h:43
A managed object in the TVM runtime.
Type-erased function used across TVM API.
This file defines the TVM global function registry.
Runtime container of the functions generated by TVM, This is used to support dynamically link,...
@ kDynamic
Type index is allocated during runtime.
Definition: object.h:80
A single virtual machine instruction.
Definition: bytecode.h:83
A representation of a stack frame.
Definition: vm.h:112
Index args
The number of arguments.
Definition: vm.h:118
RegName caller_return_register
Register in caller's frame to put return value.
Definition: vm.h:126
std::vector< ObjectRef > register_file
Statically allocated space for objects.
Definition: vm.h:123
const Instruction * code
A pointer into the caller function's instructions.
Definition: vm.h:120
VMFrame(Index pc, Index func_index, Index args, const Instruction *code, Index register_file_size)
Definition: vm.h:128
Index func_index
The index into the function table, points to the caller.
Definition: vm.h:116
Index pc
The return program counter.
Definition: vm.h:114
A representation of a Relay function in the VM.
Definition: vm.h:77
std::vector< Instruction > instructions
The instructions representing the function.
Definition: vm.h:83
friend std::ostream & operator<<(std::ostream &os, const VMFunction &)
Index register_file_size
The size of the frame for this function.
Definition: vm.h:85
std::vector< std::string > params
The function parameter names.
Definition: vm.h:81
std::string name
The function's name.
Definition: vm.h:79
VMFunction(std::string name, std::vector< std::string > params, std::vector< Instruction > instructions, Index register_file_size, std::vector< Index > param_device_indexes)
Definition: vm.h:89
std::vector< Index > param_device_indexes
The indexes for the device holding each function parameter.
Definition: vm.h:87