{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# RusTorch CoreML 통합 - Python 바인딩\n",
"\n",
"이 노트북은 Python 바인딩을 통해 RusTorch의 CoreML 기능을 사용하는 방법을 보여줍니다."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 설정 및 임포트"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# RusTorch Python 바인딩 임포트\n",
"try:\n",
" import rustorch\n",
" print(f\"✅ RusTorch 버전: {rustorch.__version__}\")\n",
" print(f\"📝 설명: {rustorch.__description__}\")\n",
" print(f\"👥 작성자: {rustorch.__author__}\")\n",
"except ImportError as e:\n",
" print(f\"❌ RusTorch 임포트 실패: {e}\")\n",
" print(\"maturin develop로 빌드해주세요\")\n",
" exit(1)\n",
"\n",
"import numpy as np\n",
"import platform\n",
"\n",
"print(f\"🖥️ 플랫폼: {platform.system()} {platform.release()}\")\n",
"print(f\"🐍 Python 버전: {platform.python_version()}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CoreML 가용성 확인"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# CoreML 기능 확인\n",
"try:\n",
" # CoreML 사용 가능 여부 확인\n",
" coreml_available = rustorch.is_coreml_available()\n",
" print(f\"🍎 CoreML 사용 가능: {coreml_available}\")\n",
" \n",
" if coreml_available:\n",
" print(\"🎉 CoreML을 사용할 수 있습니다!\")\n",
" \n",
" # 디바이스 정보 가져오기\n",
" device_info = rustorch.get_coreml_device_info()\n",
" print(\"📱 CoreML 디바이스 정보:\")\n",
" print(device_info)\n",
" else:\n",
" print(\"⚠️ CoreML을 사용할 수 없습니다\")\n",
" if platform.system() != \"Darwin\":\n",
" print(\"CoreML은 macOS에서만 사용 가능합니다\")\n",
" else:\n",
" print(\"CoreML 기능이 활성화되지 않았을 수 있습니다\")\n",
" \n",
"except AttributeError:\n",
" print(\"❌ CoreML 함수를 찾을 수 없습니다\")\n",
" print(\"CoreML 기능으로 빌드되지 않았을 수 있습니다\")\n",
" coreml_available = False\n",
"except Exception as e:\n",
" print(f\"❌ CoreML 확인 중 오류: {e}\")\n",
" coreml_available = False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CoreML 디바이스 생성 및 작업"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if coreml_available:\n",
" try:\n",
" # CoreML 디바이스 생성\n",
" device = rustorch.CoreMLDevice(device_id=0)\n",
" print(f\"🖥️ CoreML 디바이스 생성됨: {device}\")\n",
" \n",
" # 디바이스 정보 가져오기\n",
" print(f\"🆔 디바이스 ID: {device.device_id()}\")\n",
" print(f\"✅ 사용 가능: {device.is_available()}\")\n",
" print(f\"💾 메모리 제한: {device.memory_limit()} 바이트\")\n",
" print(f\"🧮 연산 유닛 제한: {device.compute_units_limit()}\")\n",
" print(f\"📚 모델 캐시 크기: {device.model_cache_size()}\")\n",
" \n",
" # 캐시 정리\n",
" device.cleanup_cache()\n",
" print(\"🧹 캐시 정리됨\")\n",
" \n",
" except Exception as e:\n",
" print(f\"❌ CoreML 디바이스 작업 오류: {e}\")\n",
"else:\n",
" print(\"⚠️ CoreML을 사용할 수 없어 디바이스 작업을 건너뜁니다\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CoreML 백엔드 구성"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if coreml_available:\n",
" try:\n",
" # CoreML 백엔드 구성 생성\n",
" config = rustorch.CoreMLBackendConfig(\n",
" enable_caching=True,\n",
" max_cache_size=200,\n",
" enable_profiling=True,\n",
" auto_fallback=True\n",
" )\n",
" print(f\"⚙️ 백엔드 구성: {config}\")\n",
" \n",
" # 구성 값 확인 및 수정\n",
" print(f\"📊 캐싱 활성화: {config.enable_caching}\")\n",
" print(f\"🗂️ 최대 캐시 크기: {config.max_cache_size}\")\n",
" print(f\"📈 프로파일링 활성화: {config.enable_profiling}\")\n",
" print(f\"🔄 자동 폴백: {config.auto_fallback}\")\n",
" \n",
" # 구성 수정\n",
" config.enable_profiling = False\n",
" config.max_cache_size = 150\n",
" print(f\"\\n🔧 업데이트된 구성: {config}\")\n",
" \n",
" # CoreML 백엔드 생성\n",
" backend = rustorch.CoreMLBackend(config)\n",
" print(f\"🚀 CoreML 백엔드: {backend}\")\n",
" print(f\"✅ 백엔드 사용 가능: {backend.is_available()}\")\n",
" \n",
" # 백엔드 통계 가져오기\n",
" stats = backend.get_stats()\n",
" print(f\"📊 백엔드 통계: {stats}\")\n",
" print(f\" 총 작업 수: {stats.total_operations}\")\n",
" print(f\" 캐시 히트: {stats.cache_hits}\")\n",
" print(f\" 캐시 미스: {stats.cache_misses}\")\n",
" print(f\" 폴백 작업: {stats.fallback_operations}\")\n",
" print(f\" 캐시 히트율: {stats.cache_hit_rate():.2%}\")\n",
" print(f\" 폴백율: {stats.fallback_rate():.2%}\")\n",
" print(f\" 평균 실행 시간: {stats.average_execution_time_ms:.2f}ms\")\n",
" \n",
" # 캐시 정리\n",
" backend.cleanup_cache()\n",
" print(\"\\n🧹 백엔드 캐시 정리됨\")\n",
" \n",
" except Exception as e:\n",
" print(f\"❌ CoreML 백엔드 작업 오류: {e}\")\n",
"else:\n",
" print(\"⚠️ CoreML을 사용할 수 없어 백엔드 작업을 건너뜁니다\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 기본 텐서 연산 (CPU)\n",
"\n",
"CoreML과 비교하기 위해 먼저 CPU에서 기본 연산을 수행합니다."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" # 기본 텐서 생성 및 연산\n",
" print(\"🧮 기본 텐서 연산 (CPU)\")\n",
" \n",
" # NumPy 배열에서 텐서 생성 (단순화된 인터페이스)\n",
" data_a = np.random.randn(2, 3).astype(np.float32)\n",
" data_b = np.random.randn(3, 2).astype(np.float32)\n",
" \n",
" print(f\"📐 행렬 A 형태: {data_a.shape}\")\n",
" print(f\"📐 행렬 B 형태: {data_b.shape}\")\n",
" \n",
" # NumPy로 행렬 곱셈 (비교용)\n",
" numpy_result = np.matmul(data_a, data_b)\n",
" print(f\"✅ NumPy matmul 결과 형태: {numpy_result.shape}\")\n",
" print(f\"📊 결과 (첫 번째 요소들): {numpy_result.flatten()[:4]}\")\n",
" \n",
" print(\"\\n🚀 CPU 연산 완료\")\n",
" \n",
"except Exception as e:\n",
" print(f\"❌ 텐서 연산 오류: {e}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 성능 비교 시뮬레이션"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"\n",
"def benchmark_matrix_operations():\n",
" \"\"\"다른 행렬 크기로 성능 비교\"\"\"\n",
" \n",
" sizes = [(64, 64), (128, 128), (256, 256), (512, 512)]\n",
" \n",
" print(\"🏁 성능 비교:\")\n",
" print(\"크기\\t\\tCPU 시간 (ms)\\t예상 CoreML (ms)\")\n",
" print(\"-\" * 50)\n",
" \n",
" for size in sizes:\n",
" # CPU 실행 시간 측정\n",
" a = np.random.randn(*size).astype(np.float32)\n",
" b = np.random.randn(size[1], size[0]).astype(np.float32)\n",
" \n",
" start_time = time.time()\n",
" result = np.matmul(a, b)\n",
" cpu_time = (time.time() - start_time) * 1000\n",
" \n",
" # 예상 CoreML 시간 (가상)\n",
" # 실제 구현에서는 CoreML 백엔드의 실제 측정값 사용\n",
" expected_coreml_time = cpu_time * 0.6 # 가정: CoreML이 40% 빠름\n",
" \n",
" print(f\"{size[0]}x{size[1]}\\t\\t{cpu_time:.2f}\\t\\t{expected_coreml_time:.2f}\")\n",
"\n",
"benchmark_matrix_operations()\n",
"\n",
"print(\"\\n📝 참고: CoreML 시간은 가상입니다. 실제 값은 구체적인 구현에 따라 달라집니다.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 디바이스 선택 시뮬레이션"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def simulate_device_selection():\n",
" \"\"\"스마트 디바이스 선택 시뮬레이션\"\"\"\n",
" \n",
" operations = [\n",
" (\"작은 행렬 곱셈\", (16, 16), \"CPU\"),\n",
" (\"중간 행렬 곱셈\", (128, 128), \"Metal GPU\"),\n",
" (\"큰 행렬 곱셈\", (512, 512), \"CoreML\" if coreml_available else \"Metal GPU\"),\n",
" (\"활성화 함수\", (32, 64, 128, 128), \"Metal GPU\"),\n",
" (\"작은 컨볼루션\", (1, 3, 32, 32), \"CPU\"),\n",
" (\"큰 컨볼루션\", (16, 64, 224, 224), \"CoreML\" if coreml_available else \"Metal GPU\"),\n",
" (\"복소수 연산\", (128, 128), \"Metal GPU\"), # CoreML 미지원\n",
" (\"통계 분포\", (1000,), \"CPU\"), # CoreML 미지원\n",
" ]\n",
" \n",
" print(\"🎯 스마트 디바이스 선택 시뮬레이션:\")\n",
" print(\"연산\\t\\t\\t텐서 형태\\t\\t선택된 디바이스\")\n",
" print(\"-\" * 70)\n",
" \n",
" for name, shape, device in operations:\n",
" shape_str = \"x\".join(map(str, shape))\n",
" print(f\"{name:<23}\\t{shape_str:<15}\\t{device}\")\n",
" \n",
" print(\"\\n📝 선택 논리:\")\n",
" print(\" • 작은 연산: CPU (오버헤드 방지)\")\n",
" print(\" • 중간 연산: Metal GPU (균형)\")\n",
" print(\" • 큰 연산: CoreML (최적화)\")\n",
" print(\" • 지원되지 않는 연산: GPU/CPU 폴백\")\n",
"\n",
"simulate_device_selection()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 실용적인 예제: 간단한 신경망 레이어"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def simulate_neural_network_layer():\n",
" \"\"\"신경망 레이어 시뮬레이션\"\"\"\n",
" \n",
" print(\"🧠 신경망 레이어 시뮬레이션:\")\n",
" \n",
" # 배치 크기 및 레이어 구성\n",
" batch_size = 32\n",
" input_features = 784 # 28x28 MNIST\n",
" hidden_features = 256\n",
" output_features = 10 # 10개 클래스\n",
" \n",
" print(f\"📊 배치 크기: {batch_size}\")\n",
" print(f\"🔢 입력 특성: {input_features}\")\n",
" print(f\"🧮 은닉 특성: {hidden_features}\")\n",
" print(f\"🎯 출력 특성: {output_features}\")\n",
" \n",
" # 순전파 시뮬레이션\n",
" steps = [\n",
" (\"입력 → 은닉\", f\"({batch_size}, {input_features}) @ ({input_features}, {hidden_features})\", \"CoreML\" if coreml_available else \"Metal\"),\n",
" (\"ReLU 활성화\", f\"({batch_size}, {hidden_features})\", \"Metal\"),\n",
" (\"은닉 → 출력\", f\"({batch_size}, {hidden_features}) @ ({hidden_features}, {output_features})\", \"CoreML\" if coreml_available else \"Metal\"),\n",
" (\"Softmax\", f\"({batch_size}, {output_features})\", \"CPU\"),\n",
" ]\n",
" \n",
" print(\"\\n🔄 순전파 시뮬레이션:\")\n",
" total_time = 0\n",
" \n",
" for step, shape, device in steps:\n",
" # 가상 실행 시간 (ms)\n",
" if device == \"CoreML\":\n",
" time_ms = np.random.uniform(0.5, 2.0)\n",
" elif device == \"Metal\":\n",
" time_ms = np.random.uniform(1.0, 3.0)\n",
" else: # CPU\n",
" time_ms = np.random.uniform(0.2, 1.0)\n",
" \n",
" total_time += time_ms\n",
" print(f\" {step:<15} {shape:<30} {device:<8} {time_ms:.2f}ms\")\n",
" \n",
" print(f\"\\n⏱️ 총 순전파 시간: {total_time:.2f}ms\")\n",
" print(f\"🚀 예상 처리량: {1000/total_time:.0f} 배치/초\")\n",
"\n",
"simulate_neural_network_layer()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 요약 및 다음 단계"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"📋 RusTorch CoreML 통합 요약:\")\n",
"print()\n",
"print(\"✅ 완료된 항목:\")\n",
"print(\" • Jupyter 환경 설정\")\n",
"print(\" • Rust 커널 및 Python 바인딩 생성\")\n",
"print(\" • CoreML 가용성 확인\")\n",
"print(\" • 디바이스 관리 및 구성\")\n",
"print(\" • 백엔드 통계 및 프로파일링\")\n",
"print(\" • 스마트 디바이스 선택\")\n",
"print()\n",
"print(\"🚧 향후 개발:\")\n",
"print(\" • 실제 CoreML 연산 구현\")\n",
"print(\" • 성능 벤치마킹\")\n",
"print(\" • 더 많은 활성화 함수 및 레이어 타입\")\n",
"print(\" • 오류 처리 개선\")\n",
"print(\" • 메모리 최적화\")\n",
"print()\n",
"print(\"🎯 권장 다음 단계:\")\n",
"print(\" 1. 실제 CoreML 모델 로드 및 테스트\")\n",
"print(\" 2. Metal과 CoreML 성능 비교\")\n",
"print(\" 3. 실제 딥러닝 워크플로우로 테스트\")\n",
"print(\" 4. 프로덕션 환경에서 평가\")\n",
"\n",
"if coreml_available:\n",
" print(\"\\n🎉 축하합니다! CoreML을 사용할 수 있으며 모든 기능을 테스트할 수 있습니다.\")\n",
"else:\n",
" print(\"\\n⚠️ CoreML을 사용할 수 없지만 기본 기능은 작동합니다.\")\n",
" print(\" macOS에서 CoreML 기능을 활성화하여 빌드하는 것을 권장합니다.\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}