Repository: pytorch
Issue: Can not translate Llama model to MLIR
Labels: triaged,oncall: pt2,export-triaged,oncall: export

### 🐛 Describe the bug

I use the following script to translate Llama-2-7b-hf to MLIR. It failed in the translation to torchscript.
```python
  from transformers import AutoTokenizer, LlamaForCausalLM
  from torch_mlir import fx
  import torch

  model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
  tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")

  prompt = "What is the capital of France?"
  inputs = tokenizer(prompt, return_tensors="pt")

  print(f"Input shape: {inputs['input_ids'].shape}")
  m = fx.export_and_import(model, torch.randn(1, 8), enable_ir_printing=True,
                           enable_graph_printing=True)
```

backtrace
```shell
Traceback (most recent call last):
  File "/home/hmsjwzb/work/tinyLlama_0927/./lamaExample.py", line 15, in <module>
    m = fx.export_and_import(model, torch.randn(1, 8), enable_ir_printing=True,
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch_mlir/fx.py", line 73, in export_and_import
    prog = torch.export.export(f, args, kwargs, dynamic_shapes=dynamic_shapes)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/export/__init__.py", line 174, in export
    return _export(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/export/_trace.py", line 946, in wrapper
    raise e
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/export/_trace.py", line 929, in wrapper
    ep = fn(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/export/exported_program.py", line 88, in wrapper
    return fn(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/export/_trace.py", line 1455, in _export
    aten_export_artifact = export_func(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/export/_trace.py", line 1060, in _strict_export
    gm_torch_level = _export_to_torch_ir(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/export/_trace.py", line 512, in _export_to_torch_ir
    gm_torch_level, _ = torch._dynamo.export(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 1350, in inner
    result_traced = opt_f(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1552, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1561, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 421, in _fn
    return fn(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1552, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1561, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1078, in catch_errors
    return callback(frame, cache_entry, hooks, frame_state, skip=1)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 456, in _convert_frame_assert
    return _compile(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_utils_internal.py", line 83, in wrapper_function
    return StrobelightCompileTimeProfiler.profile_compile_time(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_strobelight/compile_time_profiler.py", line 129, in profile_compile_time
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.10/contextlib.py", line 79, in inner
    return func(*args, **kwds)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 799, in _compile
    guarded_code = compile_inner(code, one_graph, hooks, transform)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 232, in time_wrapper
    r = func(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 618, in compile_inner
    out_code = transform_code_object(code, transform)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py", line 1184, in transform_code_object
    transformations(instructions, code_options)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 177, in _fn
    return fn(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 564, in transform
    tracer.run()
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 2450, in run
    super().run()
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 892, in run
    while self.step():
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 804, in step
    self.dispatch_table[inst.opcode](self, inst)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 498, in wrapper
    return inner_fn(self, inst)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1511, in CALL_FUNCTION_KW
    self.call_function(fn, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 742, in call_function
    self.push(fn.call_function(self, args, kwargs))
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/variables/nn_module.py", line 408, in call_function
    return tx.inline_user_function_return(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 748, in inline_user_function_return
    return InliningInstructionTranslator.inline_call(self, fn, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 2665, in inline_call
    return cls.inline_call_(parent, func, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 2781, in inline_call_
    tracer.run()
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 892, in run
    while self.step():
 File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 804, in step
    self.dispatch_table[inst.opcode](self, inst)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 498, in wrapper
    return inner_fn(self, inst)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1499, in CALL_FUNCTION_EX
    self.call_function(fn, argsvars.items, kwargsvars)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 742, in call_function
    self.push(fn.call_function(self, args, kwargs))
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/variables/functions.py", line 342, in call_function
    return super().call_function(tx, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/variables/functions.py", line 294, in call_function
    return super().call_function(tx, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/variables/functions.py", line 91, in call_function
    return tx.inline_user_function_return(self, [*self.self_args(), *args], kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 748, in inline_user_function_return
    return InliningInstructionTranslator.inline_call(self, fn, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 2665, in inline_call
    return cls.inline_call_(parent, func, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 2781, in inline_call_
    tracer.run()
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 892, in run
    while self.step():
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 804, in step
    self.dispatch_table[inst.opcode](self, inst)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 498, in wrapper
    return inner_fn(self, inst)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1458, in CALL_FUNCTION
    self.call_function(fn, args, {})
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 742, in call_function
    self.push(fn.call_function(self, args, kwargs))
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/variables/nn_module.py", line 380, in call_function
    return wrap_fx_proxy(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 1713, in wrap_fx_proxy
    return wrap_fx_proxy_cls(target_cls=TensorVariable, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 1798, in wrap_fx_proxy_cls
    example_value = get_fake_value(proxy.node, tx, allow_non_graph_fake=True)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 1854, in get_fake_value
    raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 1786, in get_fake_value
    ret_val = wrap_fake_exception(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 1301, in wrap_fake_exception
    return fn()
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 1787, in <lambda>
    lambda: run_node(tx.output, node, args, kwargs, nnmodule)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 1922, in run_node
    raise RuntimeError(make_error_message(e)).with_traceback(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 1909, in run_node
    return nnmodule(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1552, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1561, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/sparse.py", line 163, in forward
    return F.embedding(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/functional.py", line 2267, in embedding
    return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/utils/_stats.py", line 20, in wrapper
    return fn(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1060, in __torch_dispatch__
    return self.dispatch(func, types, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1449, in dispatch
    return self._cached_dispatch_impl(func, types, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1144, in _cached_dispatch_impl
    output = self._dispatch_impl(func, types, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1689, in _dispatch_impl
    return decomposition_table[func](*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_prims_common/wrappers.py", line 265, in _fn
    result = fn(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_decomp/decompositions.py", line 1179, in embedding
    return weight[indices]
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/utils/_stats.py", line 20, in wrapper
    return fn(*args, **kwargs)
 File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1060, in __torch_dispatch__
    return self.dispatch(func, types, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1449, in dispatch
    return self._cached_dispatch_impl(func, types, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1152, in _cached_dispatch_impl
    output = self._dispatch_impl(func, types, args, kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1729, in _dispatch_impl
    op_impl_out = op_impl(self, func, *args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_impls.py", line 150, in dispatch_to_op_implementations_dict
    return op_implementations_dict[func](fake_mode, func, *args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_subclasses/fake_impls.py", line 549, in index_tensor
    out = meta_index_Tensor(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/_meta_registrations.py", line 2988, in meta_index_Tensor
    torch._check(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/__init__.py", line 1200, in _check
    _check_with(RuntimeError, cond, message)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/__init__.py", line 1183, in _check_with
    raise error_type(message_evaluated)
torch._dynamo.exc.TorchRuntimeError: Failed running call_module L__self___model_embed_tokens(*(FakeTensor(..., size=(1, 8)),), **{}):
tensors used as indices must be long, int, byte or bool tensors

from user code:
   File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py", line 1208, in forward
    outputs = self.model(
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1561, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/hmsjwzb/work/selfPython/ai/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py", line 974, in forward
    inputs_embeds = self.embed_tokens(input_ids)
```

### Versions

```shell
Collecting environment information...
PyTorch version: 2.4.0.dev20240604+cpu
Is debug build: False
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 18.1.8 (/home/hmsjwzb/code/llvm-project/clang 443e23eed24d9533566f189ef25154263756a36d)
CMake version: version 3.30.3
Libc version: glibc-2.35

Python version: 3.10.15+ (heads/3.10:0c5fc272175, Sep 24 2024, 11:33:24) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.8.0-45-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 12.6.68
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        46 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               32
On-line CPU(s) list:                  0-31
Vendor ID:                            GenuineIntel
Model name:                           13th Gen Intel(R) Core(TM) i9-13900
CPU family:                           6
Model:                                183
Thread(s) per core:                   2
Core(s) per socket:                   24
Socket(s):                            1
Stepping:                             1
CPU max MHz:                          5600.0000
CPU min MHz:                          800.0000
BogoMIPS:                             3993.60
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            896 KiB (24 instances)
L1i cache:                            1.3 MiB (24 instances)
L2 cache:                             32 MiB (12 instances)
L3 cache:                             36 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-31
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Mitigation; Clear Register File
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] torch==2.4.0.dev20240604+cpu
[pip3] torchaudio==2.4.1
[pip3] torchvision==0.19.1
[pip3] triton==2.0.0
[conda] magma-cuda121             2.6.1                         1    pytorch
```

cc @ezyang @chauhang @penguinwu @avikchaudhuri @gmagogsfm @zhxchen17 @tugsbayasgalan @angelayi @suo @ydwu4