我想给出一个比较完整的答案。

首先:

这段代码可以使用(py)OpenCL在GPU上运行吗?

很可能是的。

这能自动完成吗?

不(阿飞)。

关于OpenCL,我得到的大多数问题都是这样的:“为了加快速度,值得将这段代码移植到OpenCL吗?”您声明,您的外部循环独立于其他运行的结果,这使得代码基本上可并行化。在一个简单的实现中,每个OpenCL工作元素将使用稍有不同的输入参数执行相同的代码。不考虑主机和设备之间数据传输的开销,这种方法的运行时间将等于最慢迭代的运行时间。根据你外循环中的迭代,这可能是一个巨大的速度增益。只要数字保持相对较小,您可以尝试

multiprocessing

在python中的模块,在CPU而不是GPU上并行化这些迭代。

移植到GPU通常只有在大量进程并行运行(大约1000个或更多)时才有意义。所以在你的例子中,如果你真的想要一个巨大的速度提升,看看你是否可以并行化所有的计算

里面

循环。例如,您有150个迭代和2000个数据点。如果你能以某种方式将这2000个数据点并行化,这将提供更大的速度增益,这可以证明将整个代码移植到OpenCL的工作是正确的。

TL;博士:

先在CPU上尝试并行化。如果您发现需要同时运行多个100秒的进程,请转到GPU。

更新:

使用多处理(不带回调)在CPU上并行化的简单代码

import numpy as np

import time

import multiprocessing as mp

m = 3 # Dimension of datapoints

num_points = 2000 # Number of datapoints

iterMax = 150 # Maximum number of iterations

NMax = 10 # Maximum number of neurons

#%%

np.random.seed(0)

y = np.random.rand(num_points,m) # Generate always the same dataset

sigma_0 = 5 # Initial value of width of the neighborhood function

eta_0 = 1 # Initial value of learning rate

w = list(range(NMax - 1))

wClusters = np.zeros((np.size(y,axis = 0),NMax - 1)) # Clusters for each N

def neuron_run(N):

w[N] = np.random.uniform(0,1,(N+2,np.size(y,axis=1))) - 0.5 # Initialize weights

iterCount = 1

while iterCount < iterMax:

# Mix up the input patterns

mixInputs = y[np.random.permutation(np.size(y,axis = 0)),:]

# Sigma reduction

sigma = sigma_0 - (sigma_0/(iterMax + 1)) * iterCount

s2 = 2*sigma**2

# Learning rate reduction

eta = eta_0 - (eta_0/(iterMax + 1)) * iterCount

for selectedInput in mixInputs: # Pick up one pattern

# Search winning neuron

aux = np.sum((selectedInput - w[N])**2, axis = -1)

ii = np.argmin(aux) # Neuron 'ii' is the winner

jjs = abs(ii - list(range(N+2)))

dists = np.min(np.vstack([jjs , abs(jjs-(N+2))]), axis = 0)

# Update weights

w[N] = w[N] + eta * np.exp((-dists**2)/s2).T[:,np.newaxis] * (selectedInput - w[N])

print(N+2,iterCount)

iterCount += 1

# Assign each datapoint to its nearest neuron

for kk in range(np.size(y,axis = 0)):

aux = np.sum((y[kk,] - w[N])**2,axis=-1)

ii = np.argmin(aux) # Neuron 'ii' is the winner

wClusters[kk,N] = ii + 1

t_begin = time.clock() # Start time

#%%

def apply_async():

pool = mp.Pool(processes=NMax)

for N in range(NMax-1):

pool.apply_async(neuron_run, args = (N,))

pool.close()

pool.join()

print "Multiprocessing done!"

if __name__ == '__main__':

apply_async()

t_end = time.clock() # End time

print(t_end - t_begin)

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐