MagooDB commited on
Commit
3b2c794
·
verified ·
1 Parent(s): d0ae976

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +182 -0
app.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from typing import TypedDict
3
+ from langgraph.graph import StateGraph, START, END
4
+ from langchain_openai import ChatOpenAI
5
+
6
+ class MigrationState(TypedDict):
7
+ codigo_original: str
8
+ codigo_traducido: str
9
+ analisis_seguridad: str
10
+
11
+ # Nota: El código trabaja actualmente con el modelo DeepSeek V3.1.
12
+ # Sin embargo, se recomienda trabajar con Qwen2.5-Coder 32B para un mejor análisis de código.
13
+ llm = ChatOpenAI(
14
+ api_key="API_KEY",
15
+ base_url="https://api.fireworks.ai/inference/v1",
16
+ model="accounts/fireworks/models/deepseek-v3p1"
17
+ )
18
+
19
+ def nodo_traductor(state: MigrationState):
20
+ prompt = f"Actúa como un experto en AMD ROCm. Traduce este código NVIDIA CUDA a AMD HIP. Solo devuelve el código final, sin explicaciones:\n\n{state['codigo_original']}"
21
+ respuesta = llm.invoke(prompt)
22
+
23
+ codigo_limpio = respuesta.content
24
+ if codigo_limpio.startswith("```"):
25
+ lineas = codigo_limpio.split("\n")
26
+ codigo_limpio = "\n".join(lineas[1:-1])
27
+
28
+ return {"codigo_traducido": codigo_limpio}
29
+
30
+ def nodo_auditor(state: MigrationState):
31
+ prompt = f"Revisa este código AMD HIP. Confirma si la migración fue correcta y advierte sobre posibles fugas de memoria. Sé breve (máximo 3 líneas):\n\n{state['codigo_traducido']}"
32
+ respuesta = llm.invoke(prompt)
33
+ return {"analisis_seguridad": respuesta.content}
34
+
35
+ workflow = StateGraph(MigrationState)
36
+ workflow.add_node("traductor", nodo_traductor)
37
+ workflow.add_node("auditor", nodo_auditor)
38
+ workflow.add_edge(START, "traductor")
39
+ workflow.add_edge("traductor", "auditor")
40
+ workflow.add_edge("auditor", END)
41
+
42
+ agente_rocm = workflow.compile()
43
+
44
+ DUMMY_CUDA_CODE = """#include <iostream>
45
+
46
+ __global__ void vectorAdd(const float *A, const float *B, float *C, int numElements) {
47
+ int i = blockDim.x * blockIdx.x + threadIdx.x;
48
+ if (i < numElements) {
49
+ C[i] = A[i] + B[i];
50
+ }
51
+ }
52
+
53
+ int main() {
54
+ return 0;
55
+ }
56
+ """
57
+
58
+ def leer_archivo(archivo):
59
+ if archivo is not None:
60
+ try:
61
+ with open(archivo.name, "r", encoding="utf-8") as f:
62
+ return f.read()
63
+ except Exception as e:
64
+ return f"Error al leer el archivo: {str(e)}"
65
+ return ""
66
+
67
+ def chat_con_agente(mensaje_usuario, historial):
68
+ if not historial:
69
+ historial = []
70
+
71
+ prompt_chat = f"""Eres el Ingeniero Líder de ROCm-Sentinel.
72
+ El usuario te da esta instrucción para la migración: '{mensaje_usuario}'.
73
+ Responde en una frase corta y técnica cómo integrarás esta instrucción en el proceso de traducción a AMD HIP."""
74
+
75
+ try:
76
+ respuesta = llm.invoke(prompt_chat)
77
+ historial.append({"role": "user", "content": mensaje_usuario})
78
+ historial.append({"role": "assistant", "content": respuesta.content})
79
+ except Exception:
80
+ historial.append({"role": "user", "content": mensaje_usuario})
81
+ historial.append({"role": "assistant", "content": "Entendido. Aplicaré esas optimizaciones técnicas al código."})
82
+
83
+ return "", historial
84
+
85
+ def simular_migracion(cuda_code, historial):
86
+ if not historial: historial = []
87
+ if not cuda_code:
88
+ yield "Error: Ingresa código.", historial, "Desconocido", ""
89
+ return
90
+
91
+ historial.append({"role": "assistant", "content": "🚀 **Proceso iniciado.** El Agente Traductor está analizando los kernels de CUDA..."})
92
+ yield "Estado: Analizando Kernels...", historial, "Analizando...", ""
93
+
94
+ try:
95
+ resultado = agente_rocm.invoke({"codigo_original": cuda_code})
96
+ rocm_code = resultado["codigo_traducido"]
97
+ reporte_auditor = resultado["analisis_seguridad"]
98
+
99
+ historial.append({"role": "assistant", "content": f"✅ **Migración Exitosa.**\n\n🛡️ **Auditoría de Seguridad:**\n{reporte_auditor}"})
100
+ yield "Estado: Completado con éxito", historial, "NVIDIA CUDA (nvcc) -> AMD HIP (hipcc)", rocm_code
101
+
102
+ except Exception as e:
103
+ historial.append({"role": "assistant", "content": f"❌ Error en el flujo: {str(e)}"})
104
+ yield "Estado: Error crítico", historial, "Error", ""
105
+
106
+ with gr.Blocks() as demo:
107
+ gr.Markdown(
108
+ """
109
+ <div style='text-align: center;'>
110
+ <h1 style='color: #FF3232;'>ROCm-Sentinel</h1>
111
+ <p><strong>Advanced CUDA to AMD ROCm Migration Agent</strong></p>
112
+ </div>
113
+ """
114
+ )
115
+
116
+ with gr.Row():
117
+ with gr.Column(scale=1):
118
+ archivo_subida = gr.File(
119
+ label="📁 Subir archivo fuente",
120
+ file_types=[".cu", ".cpp", ".txt", ".h"]
121
+ )
122
+ gr.Markdown("### 📜 Código Origen (CUDA)")
123
+ input_code = gr.Code(
124
+ label="Editor de entrada",
125
+ language="cpp",
126
+ lines=15,
127
+ value=DUMMY_CUDA_CODE
128
+ )
129
+
130
+ with gr.Column(scale=1):
131
+ lenguaje_detectado = gr.Textbox(
132
+ label="🔍 Firma / Lenguaje Detectado",
133
+ interactive=False
134
+ )
135
+ estado_migracion = gr.Textbox(
136
+ label="⚡ Monitor de Proceso (Estado)",
137
+ interactive=False,
138
+ placeholder="Listo para procesar..."
139
+ )
140
+ gr.Markdown("### 🛠️ Código Migrado (AMD HIP)")
141
+ output_code = gr.Code(
142
+ label="Resultado de la migración",
143
+ language="cpp",
144
+ lines=15,
145
+ interactive=False
146
+ )
147
+
148
+ with gr.Row():
149
+ migrate_btn = gr.Button(
150
+ "🚀 INICIAR MIGRACIÓN SEGURA A ROCm",
151
+ variant="primary",
152
+ size="lg"
153
+ )
154
+
155
+ with gr.Row():
156
+ with gr.Column(scale=1):
157
+ gr.Markdown("### 🤖 Centro de Control del Agente")
158
+ chatbot = gr.Chatbot(
159
+ label="Interacción con el Agente de IA",
160
+ height=300
161
+ )
162
+ chat_input = gr.Textbox(
163
+ label="Instrucciones adicionales para el Agente",
164
+ placeholder="Ej: 'Usa memoria unificada' o 'Optimiza para hilos específicos'..."
165
+ )
166
+
167
+ archivo_subida.change(fn=leer_archivo, inputs=archivo_subida, outputs=input_code)
168
+
169
+ chat_input.submit(
170
+ fn=chat_con_agente,
171
+ inputs=[chat_input, chatbot],
172
+ outputs=[chat_input, chatbot]
173
+ )
174
+
175
+ migrate_btn.click(
176
+ fn=simular_migracion,
177
+ inputs=[input_code, chatbot],
178
+ outputs=[estado_migracion, chatbot, lenguaje_detectado, output_code]
179
+ )
180
+
181
+ if __name__ == "__main__":
182
+ demo.launch(theme=gr.themes.Monochrome())