CANN/AsNumpy快速入门指南
Quick Start【免费下载链接】asnumpy哈尔滨工业大学计算学部苏统华、王甜甜老师团队联合华为CANN团队开发的华为昇腾NPU原生Numpy仓库项目地址: https://gitcode.com/cann/asnumpyBack to README | See also: Examples | API DocumentationThis guide walks you through the basic usage of AsNumpy and shows how to migrate existing NumPy code to run on Ascend NPU with minimal changes.PrerequisitesAsNumpy installed (Installation Guide)Ascend 910B NPU with CANN 8.2.RC1.alpha003Python 3.9NumPy vs AsNumpyThe key idea:change the import, keep the rest.NumPy (CPU)AsNumpy (NPU)import numpy as np rows, cols 20000, 20000 m1 np.random.normal(0, 1, (rows, cols)) m2 np.random.normal(0, 1, (rows, cols)) # Compute on CPU product np.multiply(m1, m2) result np.sum(product) print(result)import numpy as np import asnumpy as ap rows, cols 20000, 20000 m1 np.random.normal(0, 1, (rows, cols)) m2 np.random.normal(0, 1, (rows, cols)) # Transfer to NPU m1_npu ap.ndarray.from_numpy(m1) m2_npu ap.ndarray.from_numpy(m2) # Compute on NPU product ap.multiply(m1_npu, m2_npu) result ap.sum(product) print(result.to_numpy())End-to-End Exampleimport numpy as np import asnumpy as ap # AsNumpy auto-initializes the NPU device on import # and releases it on exit (no manual init/finalize needed) # 1. Create data on CPU (NumPy) np_a np.array([1.0, 2.0, 3.0, 4.0], dtypenp.float32) np_b np.array([10.0, 20.0, 30.0, 40.0], dtypenp.float32) # 2. Transfer to NPU npu_a ap.ndarray.from_numpy(np_a) npu_b ap.ndarray.from_numpy(np_b) # 3. Run operations on NPU npu_sum ap.add(npu_a, npu_b) npu_prod ap.multiply(npu_a, npu_b) npu_total ap.sum(npu_prod) # 4. Transfer results back to CPU print(Sum: , npu_sum.to_numpy()) # [11. 22. 33. 44.] print(Prod: , npu_prod.to_numpy()) # [ 10. 40. 90. 160.] print(Total: , npu_total.to_numpy()) # 300.0 # 5. Verify against NumPy assert np.allclose(npu_sum.to_numpy(), np.add(np_a, np_b)) assert np.allclose(npu_prod.to_numpy(), np.multiply(np_a, np_b)) print(Verification passed.)Checking the Deviceimport asnumpy as ap # Query available NPU devices print(ap.get_device_count()) # e.g. 8 # Switch to a specific NPU (default is 0) ap.set_device(1)More ExamplesRunnable scripts are available inexamples/:ScriptOperation01_add.pyElement-wise addition02_exp2.pyExponentiation (2^x)03_multiply.pyElement-wise multiply (with benchmark)04_all.pyCombined operations05_divide.pyElement-wise division【免费下载链接】asnumpy哈尔滨工业大学计算学部苏统华、王甜甜老师团队联合华为CANN团队开发的华为昇腾NPU原生Numpy仓库项目地址: https://gitcode.com/cann/asnumpy创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考