dev_AI_framework
계산 그래프 구성과 백엔드 연산 부분이 수정된 Dense Layer, call 함수
명징직조지훈
2025. 1. 28. 12:31
def call(self, input_data):
"""
Dense 층의 연산을 수행합니다.
"""
if input_data.ndim != 2 or input_data.shape[1] != self.input_shape[1]:
raise ValueError(f"Invalid input shape. Expected shape (batch_size, {self.input_shape[1]}), "
f"but got {input_data.shape}.")
# 행렬 곱셈 연산
x, self.node_list = operations_matrix.matrix_multiply(input_data, self.weights)
# 편향 추가
if self.bias is not None:
bias_reshaped = np.tile(self.bias, (input_data.shape[0], 1))
x, add_node_list = operations_matrix.matrix_add(x, bias_reshaped)
# add_node_list 의 각 원소의 리프 노드 탐색 후 연결수행
for i in range(len(self.node_list)):
leaf_node = add_node_list[i].find_leaf_nodes()[0]
root_node = self.node_list[i]
root_node.add_parent(leaf_node)
leaf_node.add_child(root_node)
# 활성화 함수 적용
if self.activation is not None:
x, act_node_list = self.activation(x)
for i in range(len(self.node_list)):
leaf_node = act_node_list[i].find_leaf_nodes()[0]
root_node = self.node_list[i]
root_node.add_parent(leaf_node)
leaf_node.add_child(root_node)
return x.reshape(1,-1)
기존의 Dense Layer 에서 수정이 필요
이전의 방법에선 백엔드, C++ 내에서 계산 그래프의 구성과 행렬 연산이 모두 실행되었음
바뀐 방법, 행렬 연산의 부분만 C++ 내에서 구현, 계산 그래프의 경우 python 으로 구현한 node class 를 사용하여 구성하는 방법으로 변경할 것임
def call(self, input_data):
"""
Dense 층의 연산을 수행합니다.
연산 수행 과정을 수정하자
"""
if input_data.ndim != 2 or input_data.shape[1] != self.input_shape[1]:
raise ValueError(f"Invalid input shape. Expected shape (batch_size, {self.input_shape[1]}), "
f"but got {input_data.shape}.")
# 행렬 곱셈 연산, 결과를 저장할 result 행렬을 미리 생성한다.
result = np.zeros(input_data.shape[0], self.weights[1])
matrix_ops.matrix_mul(input_data, self.weights, result)
# 편향 추가
if self.bias is not None:
# 편향 값을 행렬로 변환
bias_reshaped = np.tile(self.bias, (input_data.shape[0], 1))
matrix_ops.matrix_add(result, bias_reshaped, result)
"""
활성화 함수 적용 부분 수정 필요
"""
if self.activation is not None:
x, act_node_list = self.activation(x)
return x.reshape(1,-1)
바뀐 call 연산 중 일부,
단순 행렬 연산의 backend 내에서 실행,
계산 그래프의 생성 부분의 수정 필요