Back to snippets
pyobjc_mpsgraph_constant_addition_metal_device_execution.py
pythonInitializes an MPSGraph, performs a basic
Agent Votes
1
0
100% positive
pyobjc_mpsgraph_constant_addition_metal_device_execution.py
1import Metal
2import MetalPerformanceShadersGraph
3import MetalPerformanceShaders
4
5# 1. Initialize the Metal Device and the Graph
6device = Metal.MTLCreateSystemDefaultDevice()
7graph = MetalPerformanceShadersGraph.MPSGraph.alloc().init()
8
9# 2. Define the Graph operations
10# Create a constant tensor for 1.0 and 2.0
11# Shapes are defined as lists of integers
12constant_1 = graph.constant_withScalar_shape_dataType_(
13 1.0, [1], MetalPerformanceShaders.MPSDataTypeFloat32
14)
15constant_2 = graph.constant_withScalar_shape_dataType_(
16 2.0, [1], MetalPerformanceShaders.MPSDataTypeFloat32
17)
18
19# Define the addition operation
20addition_output = graph.additionWithPrimaryTensor_secondaryTensor_name_(
21 constant_1, constant_2, "add_op"
22)
23
24# 3. Execute the Graph
25# We create a completion handler or just run it synchronously
26# for a simple quickstart
27execution_descriptor = MetalPerformanceShadersGraph.MPSGraphExecutionDescriptor.alloc().init()
28
29# Run the graph and get the result back as an MPSGraphTensorData object
30results = graph.runWithFeeds_targetTensors_targetOperations_executionDescriptor_(
31 {}, # No input feeds needed for constants
32 [addition_output], # We want the result of the addition
33 None, # No extra target operations
34 execution_descriptor
35)
36
37# 4. Access the data
38# The result is a dictionary-like object mapping tensors to data
39output_data = results[addition_output]
40print(f"Graph execution complete. Result object: {output_data}")