You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

mgb_helper.py 2.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. """helper utils for the core mgb module"""
  10. import collections
  11. import inspect
  12. import json
  13. import threading
  14. from abc import ABCMeta, abstractmethod
  15. class callback_lazycopy:
  16. """wraps around a callable to be passed to :meth:`.CompGraph.compile`.
  17. This is used to disable eager copy, so we could get rid of an h2d copy and
  18. a d2h if values are to be passed from one callback to another
  19. :class:`.SharedND`.
  20. """
  21. def __init__(self, func):
  22. assert isinstance(func, collections.Callable)
  23. self.__func = func
  24. @property
  25. def func(self):
  26. return self.__func
  27. class SharedNDLazyInitializer(metaclass=ABCMeta):
  28. """lazy initialization policy for :class:`.SharedND`"""
  29. @abstractmethod
  30. def get_shape(self):
  31. """get shape, without loading value"""
  32. @abstractmethod
  33. def get_value(self):
  34. """get value as numpy ndarray"""
  35. class copy_output:
  36. """wraps a :class:`.SymbolVar` in outspec for :meth:`.CompGraph.compile`,
  37. to copy the output to function return value"""
  38. symvar = None
  39. borrow_mem = None
  40. def __init__(self, symvar, *, borrow_mem=False):
  41. """
  42. :param borrow_mem: see :meth:`.CompGraphCallbackValueProxy.get_value`
  43. """
  44. from .mgb import SymbolVar
  45. assert isinstance(
  46. symvar, SymbolVar
  47. ), "copy_output expects an SymbolVar, got {} instead".format(symvar)
  48. self.symvar = symvar
  49. self.borrow_mem = borrow_mem
  50. class FuncOutputSaver:
  51. """instance could be used as callbacks for :meth:`.CompGraph.compile` to
  52. copy output to host buffer
  53. """
  54. _value = None
  55. _borrow_mem = None
  56. def __init__(self, borrow_mem=False):
  57. self._borrow_mem = borrow_mem
  58. def __call__(self, v):
  59. self._value = v.get_value(borrow_mem=self._borrow_mem)
  60. def get(self):
  61. assert (
  62. self._value is not None
  63. ), "{} not called; maybe due to unwaited async func".format(self)
  64. return self._value

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台