Vitis AI 분석 — DPU·xmodel·VART
#한 줄 요약
**“Vitis AI는 DPU(Deep Learning Processor Unit)라는 Xilinx의 INT8 inference 엔진과 그것을 위한 toolchain입니다.” TensorFlow/PyTorch 모델을 quantize → compile → xmodel → VART로 실행합니다.
#어떤 상황에서 쓰나
Zynq UltraScale+ MPSoC, Kria K26 SoM, Versal AI 장착 device에서 neural network inference를 돌릴 때 사실상 표준입니다. ZCU104, KV260 같은 dev kit이 대표 플랫폼입니다.
GPU·NPU 없이 FPGA fabric으로 deep learning을 하면서 INT8 throughput과 낮은 전력을 챙기는 게 핵심입니다. ResNet-50을 KV260에서 ~150 fps @ 5W 정도로 돌립니다.
#핵심 개념 — DPU
DPU = Deep Learning Processing Unit- Xilinx의 IP block (RTL)- FPGA fabric에 instantiate- INT8 가속 (convolution, pool, FC, activation, ...)- DPUCZDX8G: Zynq UltraScale+- DPUCAHX8H: Alveo- DPUCVDX8G: VersalDPU는 고정된 instruction set을 가진 softcore accelerator입니다. xmodel은 DPU instruction stream. CPU instruction과 비슷한 관계입니다.
DPU 옵션:
| 옵션 | 성능 | 용도 |
|---|---|---|
| B512 | ~256 GOPS | 작은 model |
| B1024 | — | — |
| B2304 | ~1100 GOPS | — |
| B4096 | ~2000 GOPS | ZCU104·KV260 표준 |
| B8192 | ~4000 GOPS | 대형 부서 |
LUT, DSP, BRAM 사용량이 옵션에 따라 다릅니다. KV260은 보통 B4096.
#전체 흐름
- Model 학습 (TF/PyTorch)
- Quantize (FP32 → INT8) — calibration dataset 필요
- Compile (quantized → xmodel) — DPU arch 지정
- Deploy: VART API로 실행
#Step 1 — Quantize
# PyTorchfrom pytorch_nndct.apis import torch_quantizer
model = torchvision.models.resnet50(pretrained=True)model.eval()
# input shapeinput_shape = (1, 3, 224, 224)dummy = torch.randn(input_shape)
# calibrationquantizer = torch_quantizer('calib', model, dummy, device='cpu')quant_model = quantizer.quant_model
# calibration data 100~1000장 inferencefor img in calib_loader: quant_model(img)
quantizer.export_quant_config()
# test mode로 다시quantizer = torch_quantizer('test', model, dummy, device='cpu', quant_config_file='quant_info.json')quant_model = quantizer.quant_model
# verify accuracyacc = evaluate(quant_model, val_loader)print(f"Quantized accuracy: {acc}")
# export xmodelquantizer.export_xmodel()Calibration은 대표성 있는 100~1000장. Deploy 환경 분포와 가까워야 accuracy 손실 적습니다.
#Step 2 — Compile
vai_c_xir \ --xmodel ResNet50_int.xmodel \ --arch /opt/vitis_ai/compiler/arch/DPUCZDX8G/KV260/arch.json \ --output_dir compiled \ --net_name resnet50arch.json은 DPU 인스턴스의 spec. Board마다 다름. ZCU104, KV260, custom board.
출력: compiled/resnet50.xmodel. 이게 DPU instruction stream + 가중치.
#Step 3 — VART로 실행
C++ API:
#include <vart/runner.hpp>#include <xir/graph/graph.hpp>
int main() { // Load auto graph = xir::Graph::deserialize("compiled/resnet50.xmodel"); auto subgraphs = graph->get_root_subgraph()->children_topological_sort(); auto dpu_sg = std::find_if(subgraphs.begin(), subgraphs.end(), [](const auto *s) { return s->get_attr<std::string>("device") == "DPU"; });
auto runner = vart::Runner::create_runner(*dpu_sg, "run");
// Input / output tensor info auto in_tensors = runner->get_input_tensors(); auto out_tensors = runner->get_output_tensors();
// Allocate buffers int8_t *in_buf = (int8_t*)malloc(in_tensors[0]->get_data_size()); int8_t *out_buf = (int8_t*)malloc(out_tensors[0]->get_data_size());
// Preprocess + load load_image("test.jpg", in_buf);
// Run std::vector<vart::TensorBuffer*> ins = { make_buf(in_buf, in_tensors[0]) }; std::vector<vart::TensorBuffer*> outs = { make_buf(out_buf, out_tensors[0]) }; auto job = runner->execute_async(ins, outs); runner->wait((int)job.first, -1);
// Postprocess int top = argmax_int8(out_buf, 1000); printf("class %d\n", top);}Python API도 거의 동일합니다.
import vart, xirimport numpy as np
g = xir.Graph.deserialize("compiled/resnet50.xmodel")sg = next(s for s in g.get_root_subgraph().toposort_child_subgraph() if s.get_attr("device") == "DPU")runner = vart.Runner.create_runner(sg, "run")
inputs = [np.empty(t.dims, dtype=np.int8) for t in runner.get_input_tensors()]outputs = [np.empty(t.dims, dtype=np.int8) for t in runner.get_output_tensors()]
inputs[0][:] = preprocess(img)
job = runner.execute_async(inputs, outputs)runner.wait(job)
print("top:", outputs[0].argmax())#Step 4 — Multi-thread Throughput
DPU는 한 모델 instance가 동시에 여러 frame을 in-flight로 처리. Multi-thread로 throughput을 끌어올립니다.
auto runner = vart::Runner::create_runner(dpu_sg, "run");
std::vector<std::thread> ts;for (int i = 0; i < 4; i++) { ts.emplace_back([&]() { while (running) { auto img = queue_pop(); std::vector<TensorBuffer*> ins{...}, outs{...}; auto job = runner->execute_async(ins, outs); runner->wait(job.first, -1); result_push(outs); } });}4 thread × ResNet-50 → KV260에서 ~600 fps. Single-thread 대비 4배.
#YOLOv5 예 — Detection Model
from pytorch_nndct.apis import torch_quantizerimport torch
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)model.model[-1].export = True # detect layer 분리
dummy = torch.randn(1, 3, 640, 640)quantizer = torch_quantizer('calib', model, dummy)quant_model = quantizer.quant_model
for img in calib_loader: quant_model(img)
quantizer.export_xmodel()vai_c_xir --xmodel YOLOv5s_int.xmodel \ --arch /opt/.../KV260/arch.json \ --output_dir compiled --net_name yolov5sVART 실행 후 postprocess (NMS, box decode)는 CPU에서.
#DPU와 CPU의 분담
[CPU] Preprocess (resize, normalize, BGR→RGB) ↓[DPU] Backbone, head (conv, pool, activation, ...) ↓[CPU] Postprocess (NMS, sigmoid, box decode)CPU pre/post가 bottleneck이면 OpenCV optimize, OpenMP, NEON SIMD로 가속.
#Profile
# DPU runtime profilexdputil benchmark resnet50.xmodel 1 # 1 threadxdputil benchmark resnet50.xmodel 4 # 4 threadResNet-50 KV260:1 thread: 150 fps, 6.6ms/frame4 thread: 600 fps, 6.7ms/frame (latency 동일, throughput 4×)8 thread: 750 fps, ~13ms (queue 적체)Thread 수는 core 수가 아니라 queue depth로 보면 됩니다.
#DPU IP Instantiate
Vivado에서 DPU IP를 fabric에 instantiate:
- Vivado에 Vitis-AI DPU IP 추가
- Configure: B4096, single/multi DPU, RAM/URAM usage
- AXI 연결:
M_AXI_HP4개 (DDR),M_AXI_GP(control) - Generate bitstream
- petalinux로 PetaLinux 빌드, DPU driver 포함
Pre-built KV260 / ZCU104 image가 있으니 처음에는 그걸 그대로 사용.
#자주 보는 함정
Calibration data 부족
100장 이하로 calibration하면 accuracy가 510% 떨어질 수 있음. 5001000장 권장.
Unsupported op
quantizer = torch_quantizer('calib', model, dummy)# WARNING: op 'LayerNorm' not supported by DPU → CPU subgraphDPU에서 지원 안 하는 op는 CPU로 떨어짐. 모델을 DPU-friendly하게 (BatchNorm vs LayerNorm 등) 또는 fuse.
Input shape 고정
DPU는 fixed shape만 지원. Dynamic shape 모델은 max shape으로 fixed + pad.
Multi-DPU 활용 안 함
KV260은 단일 DPU지만 ZU19EG 같은 큰 device는 2개 DPU. 두 instance를 다른 stream에 할당.
Memory bandwidth
DPU는 DDR bandwidth가 bottleneck. AXI HP 4개 모두 활용. 다른 master(camera, network)와 충돌하면 throughput 떨어짐.
CPU pre/post bottleneck
DPU: 6 ms inferenceCPU: 20 ms preprocess + 10 ms NMS = 30 ms
total: 36 ms → 28 fps (DPU 6 ms는 의미 없음)Profile으로 측정. Preprocess는 GStreamer 또는 별도 fabric block으로 가속.
#정리
- Vitis AI = DPU IP + toolchain (quantize, compile, runtime).
- Quantize: FP32 → INT8, calibration dataset 100~1000장 필요.
- Compile: quantized → xmodel (DPU instruction).
- Runtime: VART API (C++/Python).
- Multi-thread로 4× throughput 일반적.
- DPU는 FPGA fabric에 instantiate되는 softcore (RTL IP).
- B4096이 KV260·ZCU104 표준 옵션.
- CPU pre/post bottleneck을 항상 profile.
다음 편은 OpenCL on FPGA입니다.
#관련 항목
Modern Embedded Recipes · 135 of 152
- 1Modern Embedded Recipes — 모던 임베디드 실전 레시피 시리즈 소개
- 2디지털 신호 기초 — Voltage Level·Edge·Setup/Hold 분석
- 3임베디드 클럭과 타이밍 — Skew·Jitter·PLL·MMCM 분석
- 4GPIO 내부 구조 분해 — Push-Pull·Open-Drain·Schmitt Trigger
- 5UART 하드웨어 동작 분석 — Baud Rate·Framing·FIFO
- 6SPI 하드웨어 분석 — Clock Mode·MOSI/MISO·Chip Select
- 7I2C 하드웨어 분석 — Open-Drain·Clock Stretching·Arbitration
- 8ADC 동작 원리 — SAR·Sigma-Delta·Pipelined 비교
- 9DAC 동작 원리 — R-2R Ladder·Sigma-Delta·Settling Time
- 10PWM 신호 생성 분석 — Duty·Frequency·Dead Time·Center-Aligned
- 11CAN 버스 전기적 특성 — Differential·Termination·Dominant/Recessive
- 12RS-485·RS-422 차동 신호 분석 — Termination·Biasing·Topology
- 13LVDS 차동 신호 분석 — Common-Mode·Impedance·Eye Pattern
- 14ARM Cortex-M 시리즈 비교 — M0·M3·M4·M7·M33·M55 분석
- 15ARM Cortex-A 시리즈 비교 — A53·A55·A72·A78·X1 분석
- 16ARM 레지스터 구조 분석 — R0~R15·CPSR·SPSR·Banked Registers
- 17Cortex-M 예외 처리 — Vector Table·NVIC·Tail-Chaining 추적
- 18ARM 메모리 맵 분석 — Normal·Device·Strongly-Ordered Region
- 19ARM L1·L2 캐시 분석 — Set Associative·Inclusive·Maintenance
- 20ARM MPU 활용 — Region·Attribute·Privilege Separation
- 21ARM MMU 기초 분석 — Translation Table·TLB·ASID
- 22ARM TrustZone-M 기초 — Secure/Non-Secure·NSC·MPC
- 23ARM Memory Barrier 실전 — DMB·DSB·ISB·DMA·MMIO
- 24임베디드 크로스 컴파일러 분석 — GCC·Clang·Sysroot 구성
- 25C 컴파일 4단계 — Preprocess·Compile·Assemble·Link 추적
- 26ELF 파일 구조 분석 — Section·Segment·Symbol Table·DWARF
- 27링커 스크립트 기초 — SECTIONS·MEMORY·entry point
- 28링커 스크립트 고급 — Overlay·BSS·init_array·LMA/VMA
- 29임베디드 스타트업 코드 분석 — Reset_Handler·Vector Table·SystemInit
- 30C 런타임 crt0 분석 — Stack·BSS Zero·Data Copy·atexit
- 31임베디드 메모리 레이아웃 — .text·.rodata·.data·.bss·.heap·.stack
- 32임베디드 컴파일러 최적화 분석 — -O0~-O3·-Os·-LTO 비교
- 33Map 파일 분석 — Symbol·Section·Size 추적으로 코드 크기 진단
- 34Make·CMake 크로스 컴파일 — Toolchain File·Sysroot 통합
- 35임베디드 Bootloader 체인 — BootROM·SPL·U-Boot·Kernel·Secure Boot
- 36첫 bare-metal 프로그램 작성 — Linker·Startup·main의 최소 구성
- 37MMIO 레지스터 직접 접근 — volatile·Memory Map·Aliasing 분석
- 38GPIO 드라이버 직접 구현 — STM32 HAL 없이 레지스터로
- 39임베디드 클럭 설정 분석 — HSE·PLL·SYSCLK·AHB/APB 분주
- 40Cortex-M 인터럽트 핸들링 — NVIC·Priority·Vector·EXTI
- 41SysTick 타이머 활용 — 24-bit Counter·1ms Tick·delay 구현
- 42UART 드라이버 구현 — polling·interrupt·DMA 3가지 방식 비교
- 43SPI 드라이버 구현 — Master·Slave·CRC·DMA
- 44I2C 드라이버 구현 — Master·7-bit/10-bit·Clock Stretching 처리
- 45임베디드 DMA 기초 — Memory-to-Memory·Peripheral·Circular Mode
- 46저전력 모드 분석 — Sleep·Stop·Standby·Wake-up Source
- 47IWDG·WWDG 워치독 구현 — Independent vs Window 비교
- 48임베디드 Flash 프로그래밍 — Erase·Program·Read While Write
- 49DDR 초기화 실패 진단 — Timing·Calibration·Walking Bit Test
- 50PWM 출력 실전 — LED 밝기·모터 속도 제어
- 51DC 모터 제어 — H-Bridge·PWM Duty·Encoder Feedback
- 52스테퍼 모터 제어 — Full Step·Half Step·Microstepping
- 53서보 모터 제어 — PWM 1ms~2ms·Closed Loop·PID
- 54Character LCD 제어 — HD44780·4-bit Mode·Custom Char
- 55SPI OLED 제어 — SSD1306·Frame Buffer·Page 단위 갱신
- 56TFT 디스플레이 구동 — RGB565·FSMC·LTDC·DMA2D
- 57환경 센서 활용 — BME280 온습압·SHT3x·BMP180 비교
- 58IMU 센서 활용 — MPU6050·LSM6DSO·Sensor Fusion
- 59CAN 통신 구현 — bxCAN·Filter·Mailbox·CAN-FD
- 60USB Device 기초 — Descriptor·Enumeration·Endpoint·HID/CDC
- 61Ethernet MAC+PHY 통합 — RMII·lwIP·DMA Descriptor
- 62SD Card + FatFs 구현 — SPI/SDIO 모드·CSD/CID·Wear
- 63RTC 활용 — Calendar·Alarm·Wake-up Timer·Backup Domain
- 64RTOS 도입 결정 분석 — Super Loop vs RTOS 트레이드오프
- 65RTOS Task 설계 패턴 — 우선순위·스택·State Machine
- 66RTOS Scheduler 동작 분석 — Tick·Context Switch·Yield
- 67RTOS Semaphore 활용 — Binary·Counting·ISR Give
- 68RTOS Mutex 활용 — Recursive·Priority Inheritance 적용
- 69RTOS Queue 활용 — By-Value·By-Reference·Timeout 패턴
- 70RTOS Event Group 활용 — Bit Wait·Sync·Notify
- 71RTOS Software Timer 활용 — One-shot·Auto-reload·Daemon Task
- 72ISR-Safe API 설계 — Reentrant·Atomic·Defer 패턴
- 73Priority Inversion 진단·예방 — Mars Pathfinder Lesson 추적
- 74Timer Wheel 분석 — Hashed·Hierarchical·O(1) Tick
- 75RTOS 디버깅 기법 — Tracealyzer·SystemView·Stack 추적
- 76임베디드 Linux 부팅 흐름 분석 — BootROM·U-Boot·Kernel·init
- 77U-Boot 활용 — bootcmd·env·tftp·boot.scr 분석
- 78Device Tree 실전 — DTS·DTB·Overlay·Phandle 추적
- 79Device Tree Overlay 적용 — Runtime fragment·dtoverlay
- 80임베디드 커널 빌드 — defconfig·menuconfig·Image·zImage
- 81커널 모듈 기초 — init/exit·Parameter·KBuild·DKMS
- 82캐릭터 드라이버 작성 — file_operations·cdev·register_chrdev
- 83Platform 드라이버 작성 — probe·remove·of_match·DT 바인딩
- 84mmap 4가지 모드 — Anonymous·File·Shared·Huge Page
- 85epoll 실전 — LT·ET·ONESHOT·EXCLUSIVE 비교
- 86UIO·VFIO 분석 — User-Space Driver와 IOMMU 격리
- 87sysfs·configfs 활용 — kobject 기반 User 인터페이스
- 88IRQ Affinity 튜닝 — smp_affinity·isolcpus·irqbalance
- 89루트 파일시스템 구축 — Buildroot 기초·Package·Toolchain
- 90임베디드 동적 메모리 — malloc 위험·결정성·대안 분석
- 91메모리 정렬과 패딩 분석 — Natural·Strict Alignment·Trap
- 92Cache Line Alignment — alignas·Padding·SoA 적용
- 93DMA-Friendly Allocator — dma_alloc_coherent·IOMMU·Pool
- 94Zero-Copy Pipeline — DMA-BUF·sendfile·io_uring·splice
- 95NUMA Memory Topology — numactl·numa_alloc·HBM 적용
- 96SIMD 활용 분석 — Intrinsics·Auto-Vectorization·OpenMP SIMD
- 97ARM NEON 심화 — Matrix Multiply·FFT·Image Filter 적용
- 98임베디드 스택 분석 — high-water·overflow 탐지
- 99임베디드 코드 크기 최적화 — -Os·LTO·Section Garbage Collection
- 100임베디드 전력 최적화 — Sleep Mode·Clock Gating·DVFS
- 101WCET 분석 기법 — Static·Measurement·Hybrid 방법론
- 102Lock-Free Ring Buffer 구현 — SPSC·Power-of-2·Memory Order
- 103Wait-Free Signaling — Atomic Flag·Sequence·Latest-Value
- 104RCU (Read-Copy-Update) 기초 — Quiescent State·Grace Period
- 105Hazard Pointer 분석 — Lock-Free Memory Reclamation
- 106Compare-And-Swap 패턴 — Stack·Counter·Linked List 적용
- 107Atomic Operation 비용 분석 — Fence·Cache Line·Contention
- 108Spinlock vs Mutex 결정 가이드 — Context Switch·Hold Time
- 109ABA 문제 회피 — Tagged Pointer·Hazard·Generation Counter
- 110False Sharing 해결 — Cache Line Padding·SoA 적용
- 111MPMC Queue 구현 — Multi-producer Multi-consumer Lock-Free
- 112임베디드 디버깅 마인드셋 — 가설·격리·재현·이분탐색
- 113JTAG·SWD 안 붙을 때 — 핀·전압·속도·세션 진단
- 114GDB 원격 디버깅 — OpenOCD·J-Link·target remote 구성
- 115Cortex-M 하드폴트 분석 — Stacked Frame·CFSR 읽기
- 116UART 안 찍힐 때 — Bare-metal 체크리스트
- 117임베디드 부팅 실패 진단 — 단계별 Isolation
- 118인터럽트 누락·중복 진단 — Priority·Pending·Re-entry 추적
- 119메모리 오버플로우·오염 진단 — Canary·MPU·Pattern 분석
- 120타이밍·Race 진단 — Heisenbug 잡는 법
- 121통신 프로토콜 분석 — Logic Analyzer와 Protocol Decoder
- 122임베디드 로깅 시스템 설계 — 레벨·버퍼·SWO·Deferred
- 123임베디드 포스트모템 분석 — Core Dump와 Field Crash
- 124FPGA 기초 분석 — LUT·FF·BRAM·DSP 자원 구조
- 125Vivado 사용법 — Project·Constraint·Synth·Impl·Bitstream
- 126PCIe BAR 매핑 분석 — Config Space·Enumeration·MMIO 접근
- 127AXI 인터페이스 — AXI4·AXI4-Lite·AXI-Stream 비교
- 128Zynq PS-PL 통신 — GP·HP·ACP 인터페이스 선택
- 129Mailbox Protocol 분석 — Host와 Accelerator를 잇는 Doorbell
- 130Command Queue·Submission Queue — NVMe·XDMA 공통 패턴
- 131DMA Completion 메커니즘 — Interrupt·Polling·Completion Ring
- 132PCIe Streaming 분석 — BAR Type·MSI-X·Kernel Bypass
- 133Vitis HLS 분석 — Pragma·Pipeline II·Dataflow 실전 감각
- 134HLS 최적화 기법 — Pipeline·Unroll·Partition·Dataflow
- 135Vitis AI 분석 — DPU·xmodel·VART
- 136OpenCL on FPGA — Kernel·Channel·Burst Memory 분석
- 137Intel Quartus 사용법 — Platform Designer·Nios II·HLS
- 138Edge Inference 분석 — Cloud vs Edge·Latency·Privacy
- 139NPU 아키텍처 분석 — Ethos·Hexagon·Systolic Array 비교
- 140딥러닝 Quantization 분석 — PTQ·QAT·INT8·INT4·Calibration
- 141TensorRT 분석 — ONNX→Engine·FP16·INT8·DLA·Multi-Stream
- 142TFLite Micro 분석 — Op Resolver·Tensor Arena·Cortex-M
- 143ONNX Runtime 분석 — Execution Provider와 Cross-Platform 배포
- 144Edge Thermal Management — Throttling·DVFS·Fan Curve·Sustained
- 145NVIDIA Jetson 분석 — Nano·Xavier·Orin·Thor·JetPack·DLA·VPI
- 146Zero-Copy Camera Pipeline — V4L2·DMA-BUF·GPU Import·NPU 직결
- 147온디바이스 LLM 추론 — llama.cpp·GGUF·MLX·KV Cache·NPU Backend
- 148Cortex-M33 TF-M·TrustZone — Secure Firmware·PSA·MCUboot
- 149Matter·Thread 분석 — IoT 통합 표준·Commissioning·Multi-Fabric
- 150PCIe → CXL 진화 — 같은 PHY 위 cache-coherent 프로토콜 추가
- 151QEMU CXL Type 3 디바이스 에뮬레이션 — 노트북에서 CXL 개발 환경 구축
- 152Linux CXL 드라이버 분석 — cxl_pci·cxl_core·region·DAX
관련 글
Modern Embedded Recipes — 모던 임베디드 실전 레시피 시리즈 소개
HW interface 기초부터 ARM·빌드·드라이버·peripheral·RTOS·Linux·메모리·동시성·디버깅·FPGA·Edge AI까지 임베디드 12 Part 종합 cookbook 148편.
온디바이스 LLM 추론 — llama.cpp·GGUF·MLX·KV Cache·NPU Backend
4-bit 양자화된 LLM이 모바일·edge에서 동작하는 시대. llama.cpp/GGUF, Apple MLX, KV cache 메모리, 백엔드 선택을 정리합니다.
Edge Thermal Management — Throttling·DVFS·Fan Curve·Sustained
Edge AI 보드의 sustained 성능을 결정하는 thermal 한계. throttle trip, DVFS, fan curve, nvpmodel, passive cooling 설계를 정리합니다.