コード例 #1
0
    def __init__(self, program, inputs, device=None, target=None):
        if device is None:
            device = plaidml_settings.get('PLAIDML_DEVICE')
        if target is None:
            target = plaidml_settings.get('PLAIDML_TARGET')

        def make_buffer(tensor):
            # convert LogicalShape into TensorShape
            return plaidml.Buffer(device, tensor.shape.into_TensorShape())

        self._input_bindings = [(x, make_buffer(x)) for x in inputs]
        self._output_bindings = [(x, make_buffer(x)) for x in program.outputs]

        self._inputs = [x[1] for x in self._input_bindings]
        self._outputs = [x[1] for x in self._output_bindings]

        def wrap(x, y):
            return ffi.new('plaidml_binding*', [x.as_ptr(), y.as_ptr()])

        inputs = [wrap(x, y) for x, y in self._input_bindings]
        outputs = [wrap(x, y) for x, y in self._output_bindings]
        ffi_obj = ffi_call(
            lib.plaidml_compile,
            program.as_ptr(),
            device.encode(),
            target.encode(),
            len(inputs),
            inputs,
            len(outputs),
            outputs,
        )
        super(Executable, self).__init__(ffi_obj)
コード例 #2
0
 def __init__(self, program, device=None, target=None):
     self.program = program
     if device is None:
         device = plaidml_settings.get('PLAIDML_DEVICE')
     self.device = device
     if target is None:
         target = plaidml_settings.get('PLAIDML_TARGET')
     self.target = target
     self.inputs = {arg.ref: arg.buffer for arg in program.inputs if arg.buffer}
     self.outputs = {arg.ref: arg.buffer for arg in program.outputs if arg.buffer}
コード例 #3
0
    def __init__(self, program, inputs=[], outputs=[], device=None, target=None):
        if device is None:
            device = plaidml_settings.get('PLAIDML_DEVICE')
        if target is None:
            target = plaidml_settings.get('PLAIDML_TARGET')

        def wrap(x, y):
            return ffi.new('plaidml_binding*', [x.as_ptr(), y.as_ptr()])

        inputs = [wrap(x, y) for x, y in inputs]
        outputs = [wrap(x, y) for x, y in outputs]
        ffi_obj = ffi_call(
            lib.plaidml_compile,
            program.as_ptr(),
            device.encode(),
            target.encode(),
            len(inputs),
            inputs,
            len(outputs),
            outputs,
        )
        super(Executable, self).__init__(ffi_obj)
コード例 #4
0
import plaidml2.op as plaidml_op
import plaidml2.settings as plaidml_settings
from keras.backend.common import epsilon, floatx, image_data_format
from keras.backend.common import set_floatx as keras_set_floatx

logger = logging.getLogger(__name__)

# Keras needs us to keep track of unique IDs for prefix strings
# (for use with get_uid and reset_uids)
_UID_PREFIX_DICT = defaultdict(int)

_NAME_SCOPE_STACK = []

_CONV_DATA_FORMAT = ['channels_first', 'channels_last']

_device = plaidml_settings.get('PLAIDML_DEVICE')
_target = plaidml_settings.get('PLAIDML_TARGET')


def _prepend_name_scope(name, default):
    if name:
        r = '_'.join(_NAME_SCOPE_STACK + [name])
    else:
        r = '_'.join(_NAME_SCOPE_STACK + [default])
        r += '_' + str(get_uid(r))
    return r


def _normalize_data_format(data_format):
    if data_format is None:
        data_format = image_data_format()
コード例 #5
0
from keras.backend.common import epsilon, floatx, image_data_format
from keras.backend.common import set_floatx as keras_set_floatx

logger = logging.getLogger(__name__)

# Keras needs us to keep track of unique IDs for prefix strings
# (for use with get_uid and reset_uids)
_UID_PREFIX_DICT = defaultdict(int)

_NAME_SCOPE_STACK = []

_CONV_DATA_FORMAT = ['channels_first', 'channels_last']

_in_train_phase = None  # Will be initialized on first use

_device = plaidml_settings.get('PLAIDML_DEVICE')


def _prepend_name_scope(name, default):
    if name:
        r = '/'.join(_NAME_SCOPE_STACK + [name])
    else:
        r = '/'.join(_NAME_SCOPE_STACK + [default])
        r += '/' + str(get_uid(r))
    return r


def _normalize_axis(axis, ndims, name=''):
    negative_axis_given = False
    normalized_axis = axis + ndims if axis < 0 else axis
    if normalized_axis < 0 or ndims <= normalized_axis:
コード例 #6
0
def main():
    print("""
PlaidML Setup ({0})

Thanks for using PlaidML!

Some Notes:
  * Bugs and other issues: https://github.com/plaidml/plaidml
  * Questions: https://stackoverflow.com/questions/tagged/plaidml
  * Say hello: https://groups.google.com/forum/#!forum/plaidml-dev
  * PlaidML is licensed under the Apache License 2.0
 """.format(plaidml.__version__))

    devices = sorted(plaidml_exec.list_devices())
    targets = sorted(plaidml_exec.list_targets())

    if not devices:
        print("""
No OpenCL devices found. Check driver installation.
Read the helpful, easy driver installation instructions from our README:
http://github.com/plaidml/plaidml
""")
        sys.exit(-1)

    dev_idx = 0
    if len(devices) > 1:
        print("""
Multiple devices detected (You can override by setting PLAIDML_DEVICE).
Please choose a default device:
""")
        for i, device in enumerate(devices):
            print("   {} : {}".format(i + 1, device))
        choices = [str(i + 1) for i in range(len(devices))]
        dev_idx = int(choice_prompt("\nDefault device", choices, "1"))
    plaidml_settings.set('PLAIDML_DEVICE', devices[dev_idx - 1])
    device = plaidml_settings.get('PLAIDML_DEVICE')

    print()
    print("Selected device:")
    print("    {}".format(device))

    print()
    print("A target determines the compiler configuration and should be matched with your device.")
    print("Please choose a default target:")
    for i, target in enumerate(targets):
        print("   {} : {}".format(i + 1, target))
    choices = [str(i + 1) for i in range(len(targets))]
    tgt_idx = int(choice_prompt("\nDefault target", choices, "1"))
    plaidml_settings.set('PLAIDML_TARGET', targets[tgt_idx - 1])
    target = plaidml_settings.get('PLAIDML_TARGET')

    print()
    print("Selected target:")
    print("    {}".format(target))

    print()
    print("Almost done. Multiplying some matrices...")
    print("Tile code:")
    print("  function (B[X, Z], C[Z, Y]) -> (A) { A[x, y : X, Y] = +(B[x, z] * C[z, y]); }")

    shape = edsl.LogicalShape(plaidml.DType.FLOAT32, [3, 3])
    B = edsl.Tensor(shape)
    C = edsl.Tensor(shape)

    X, Y, Z = edsl.TensorDims(3)
    x, y, z = edsl.TensorIndexes(3)
    B.bind_dims(X, Z)
    C.bind_dims(Z, Y)
    A = edsl.TensorOutput(X, Y)
    A[x, y] += B[x, z] * C[z, y]

    program = edsl.Program('plaidml_setup', [A])
    plaidml_exec.run(program, [(B, np.random.rand(3, 3)), (C, np.random.rand(3, 3))])
    print("Whew. That worked.")
    print()

    settings_path = plaidml_settings.get('PLAIDML_SETTINGS')
    save = choice_prompt("Save settings to {0}".format(settings_path), ["y", "n"], "y")
    if save == "y":
        plaidml_settings.save()
    print("Success!")
    print()