code: def _dupire_local_volatility_iv(
      time,
      spot_price,
      initial_spot_price,
      implied_volatility_surface,
      discount_factor_fn,
      dividend_yield,
  ):
      """Similar to _dupire_local_volatility_prices, but uses implied vols."""
      dtype = time.dtype
  
      risk_free_rate_fn = _get_risk_free_rate_from_discount_factor(
          discount_factor_fn
      )
      risk_free_rate = tf.convert_to_tensor(
          risk_free_rate_fn(time), dtype=dtype
      )
  
      def _implied_vol(expiry_time, strike):
          return implied_volatility_surface(
              strike=strike, expiry_times=expiry_time
          )
  
      theta = _implied_vol(time, spot_price)
      d1 = tf.math.divide_no_nan(
          (
              tf.math.log(initial_spot_price / spot_price)
              + (risk_free_rate - dividend_yield + 0.5 * theta**2)
              * time
          )
          / theta,
          tf.math.sqrt(time),
      )
  
      spot_fn = lambda x: _implied_vol(time, x)
      time_fn = lambda t: _implied_vol(t, spot_price)
      dtheta_dt = lambda t: math.fwd_gradient(time_fn, t)
      dtheta_dspot = lambda x: math.fwd_gradient(spot_fn, x)
      d2theta_dspot2 = lambda x: math.fwd_gradient(dtheta_dspot, x)
  
      numerator = (
          theta**2
          + 2 * time * theta * dtheta_dt(time)
          + 2
          * (risk_free_rate - dividend_yield)
          * spot_price
          * time
          * theta
          * dtheta_dspot(spot_price)
      )
      denominator = (
          1 + spot_price * d1 * time * dtheta_dspot(spot_price)
      ) ** 2 + spot_price**2 * time * theta * (
          d2theta_dspot2(spot_price)
          - d1 * time * dtheta_dspot(spot_price) ** 2
      )
      local_volatility_squared = tf.nn.relu(
          tf.math.divide_no_nan(numerator, denominator)
      )
      return tf.math.sqrt(local_volatility_squared)
  
imports: import functools
  from typing import Any, Callable, List, Optional, Union
  import tensorflow.compat.v2
  from tf_quant_finance import black_scholes
  from tf_quant_finance import datetime
  from tf_quant_finance import math
  from tf_quant_finance import types
  from tf_quant_finance.experimental.pricing_platform.framework.market_data import volatility_surface
  from tf_quant_finance.math import interpolation
  from tf_quant_finance.math import piecewise
  from tf_quant_finance.math import random
  from tf_quant_finance.models import generic_ito_process
label_desc: Use image node_id 2 for calling a global function with example usage: _dupire_local_volatility_iv(time, spot_price, initial_spot_price, implied_volatility_surface, discount_factor_fn, dividend_yield) and returns: tf, implied_volatility_surface