Tonic commited on
Commit
61754ec
·
1 Parent(s): ebe7c27

ZeroGPU cuda issue solving

Browse files
Files changed (1) hide show
  1. app.py +18 -32
app.py CHANGED
@@ -51,9 +51,8 @@ def clear_gpu_memory():
51
  torch.cuda.empty_cache()
52
  gc.collect()
53
 
54
- @spaces.GPU(duration=180)
55
  def load_pipeline():
56
- """Load the Chronos model with GPU configuration"""
57
  global pipeline
58
  try:
59
  if pipeline is None:
@@ -61,22 +60,18 @@ def load_pipeline():
61
  print("Loading Chronos model...")
62
  pipeline = ChronosPipeline.from_pretrained(
63
  "amazon/chronos-t5-large",
64
- device_map="auto", # Let the machine choose the best device
65
- torch_dtype=torch.float16, # Use float16 for better memory efficiency
66
  low_cpu_mem_usage=True,
67
- trust_remote_code=True, # Required for Chronos models
68
- use_safetensors=True # Use safetensors for better loading
69
  )
70
  # Set model to evaluation mode
71
  pipeline.model = pipeline.model.eval()
72
- # Move entire model to CUDA
73
- pipeline.model = pipeline.model.cuda()
74
  # Disable gradient computation
75
  for param in pipeline.model.parameters():
76
  param.requires_grad = False
77
  print("Chronos model loaded successfully")
78
- print(f"Model device: {next(pipeline.model.parameters()).device}")
79
- print(f"Model dtype: {next(pipeline.model.parameters()).dtype}")
80
  return pipeline
81
  except Exception as e:
82
  print(f"Error loading pipeline: {str(e)}")
@@ -284,7 +279,7 @@ def calculate_bollinger_bands(prices: pd.Series, period: int = 20, std_dev: int
284
  @spaces.GPU(duration=180)
285
  def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5, strategy: str = "chronos") -> Tuple[Dict, go.Figure]:
286
  """
287
- Make prediction using selected strategy.
288
 
289
  Args:
290
  symbol (str): Stock symbol
@@ -302,24 +297,20 @@ def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5
302
  if strategy == "chronos":
303
  try:
304
  # Prepare data for Chronos
305
- # Use Close prices for prediction
306
  prices = df['Close'].values
307
-
308
- # Normalize the data using MinMaxScaler
309
  normalized_prices = scaler.fit_transform(prices.reshape(-1, 1)).flatten()
310
 
311
- # Ensure we have enough data points and pad if necessary
312
- min_data_points = 64 # Minimum required by Chronos
313
  if len(normalized_prices) < min_data_points:
314
- # Pad the data with the last value
315
  padding = np.full(min_data_points - len(normalized_prices), normalized_prices[-1])
316
  normalized_prices = np.concatenate([padding, normalized_prices])
317
  elif len(normalized_prices) > min_data_points:
318
- # Take the most recent data points
319
  normalized_prices = normalized_prices[-min_data_points:]
320
 
321
- # Make prediction with GPU acceleration
322
  pipe = load_pipeline()
 
323
 
324
  # Get the model's device and dtype
325
  device = next(pipe.model.parameters()).device
@@ -332,21 +323,16 @@ def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5
332
 
333
  # Adjust prediction length based on timeframe
334
  if timeframe == "1d":
335
- max_prediction_length = 64 # Maximum 64 days for daily data
336
  elif timeframe == "1h":
337
- max_prediction_length = 168 # Maximum 7 days (168 hours) for hourly data
338
  else: # 15m
339
- max_prediction_length = 192 # Maximum 2 days (192 15-minute intervals) for 15m data
340
 
341
- # Convert prediction_days to appropriate intervals
342
- if timeframe == "1d":
343
- actual_prediction_length = min(prediction_days, max_prediction_length)
344
- elif timeframe == "1h":
345
- actual_prediction_length = min(prediction_days * 24, max_prediction_length)
346
- else: # 15m
347
- actual_prediction_length = min(prediction_days * 96, max_prediction_length)
348
 
349
- # Ensure prediction length is at least 1
350
  actual_prediction_length = max(1, actual_prediction_length)
351
 
352
  with torch.inference_mode():
@@ -356,7 +342,7 @@ def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5
356
 
357
  # Ensure context is properly formatted for Chronos
358
  if len(context.shape) == 1:
359
- context = context.unsqueeze(0) # Add batch dimension
360
 
361
  # Verify device and dtype
362
  print(f"Context device: {context.device}")
@@ -395,7 +381,7 @@ def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5
395
  upper_bound = scaler.inverse_transform(quantiles[0, :, 2].reshape(-1, 1)).flatten()
396
 
397
  # Calculate standard deviation from quantiles
398
- std_pred = (upper_bound - lower_bound) / (2 * 1.645) # 90% confidence interval
399
 
400
  # If we had to limit the prediction length, extend the prediction
401
  if actual_prediction_length < prediction_days:
 
51
  torch.cuda.empty_cache()
52
  gc.collect()
53
 
 
54
  def load_pipeline():
55
+ """Load the Chronos model without GPU configuration"""
56
  global pipeline
57
  try:
58
  if pipeline is None:
 
60
  print("Loading Chronos model...")
61
  pipeline = ChronosPipeline.from_pretrained(
62
  "amazon/chronos-t5-large",
63
+ device_map="cpu", # Start with CPU
64
+ torch_dtype=torch.float16,
65
  low_cpu_mem_usage=True,
66
+ trust_remote_code=True,
67
+ use_safetensors=True
68
  )
69
  # Set model to evaluation mode
70
  pipeline.model = pipeline.model.eval()
 
 
71
  # Disable gradient computation
72
  for param in pipeline.model.parameters():
73
  param.requires_grad = False
74
  print("Chronos model loaded successfully")
 
 
75
  return pipeline
76
  except Exception as e:
77
  print(f"Error loading pipeline: {str(e)}")
 
279
  @spaces.GPU(duration=180)
280
  def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5, strategy: str = "chronos") -> Tuple[Dict, go.Figure]:
281
  """
282
+ Make prediction using selected strategy with ZeroGPU.
283
 
284
  Args:
285
  symbol (str): Stock symbol
 
297
  if strategy == "chronos":
298
  try:
299
  # Prepare data for Chronos
 
300
  prices = df['Close'].values
 
 
301
  normalized_prices = scaler.fit_transform(prices.reshape(-1, 1)).flatten()
302
 
303
+ # Ensure we have enough data points
304
+ min_data_points = 64
305
  if len(normalized_prices) < min_data_points:
 
306
  padding = np.full(min_data_points - len(normalized_prices), normalized_prices[-1])
307
  normalized_prices = np.concatenate([padding, normalized_prices])
308
  elif len(normalized_prices) > min_data_points:
 
309
  normalized_prices = normalized_prices[-min_data_points:]
310
 
311
+ # Load pipeline and move to GPU
312
  pipe = load_pipeline()
313
+ pipe.model = pipe.model.cuda()
314
 
315
  # Get the model's device and dtype
316
  device = next(pipe.model.parameters()).device
 
323
 
324
  # Adjust prediction length based on timeframe
325
  if timeframe == "1d":
326
+ max_prediction_length = 64
327
  elif timeframe == "1h":
328
+ max_prediction_length = 168
329
  else: # 15m
330
+ max_prediction_length = 192
331
 
332
+ actual_prediction_length = min(prediction_days, max_prediction_length) if timeframe == "1d" else \
333
+ min(prediction_days * 24, max_prediction_length) if timeframe == "1h" else \
334
+ min(prediction_days * 96, max_prediction_length)
 
 
 
 
335
 
 
336
  actual_prediction_length = max(1, actual_prediction_length)
337
 
338
  with torch.inference_mode():
 
342
 
343
  # Ensure context is properly formatted for Chronos
344
  if len(context.shape) == 1:
345
+ context = context.unsqueeze(0)
346
 
347
  # Verify device and dtype
348
  print(f"Context device: {context.device}")
 
381
  upper_bound = scaler.inverse_transform(quantiles[0, :, 2].reshape(-1, 1)).flatten()
382
 
383
  # Calculate standard deviation from quantiles
384
+ std_pred = (upper_bound - lower_bound) / (2 * 1.645)
385
 
386
  # If we had to limit the prediction length, extend the prediction
387
  if actual_prediction_length < prediction_days: